From 6ec7d73a5a8e8a92d2c47e830553d2f35a3e66ce Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 16 Nov 2026 06:19:37 -0800 Subject: [PATCH 001/151] Color: the largest OKLCH chroma that fits sRGB is found past a gap Along a hue at a given lightness, sRGB can hold two runs of chroma with chromas outside it between them (near blue, a run of low chroma and one ending at the blue primary). max_chroma bisected as if sRGB held one run, so at blue's lightness and hue it gave about 0.266 instead of the primary's 0.3132, and a request for full chroma came out desaturated. - The search now finds where each linear sRGB component's cubic reaches an edge of the gamut, tests the chromas between those points from the top down, and refines the highest run that fits. - from_oklch lowers a chroma outside sRGB to the largest chroma under it that fits, so a chroma in the gap goes to the top of the run under it instead of being clamped channel by channel. - The C track of OKLCH Sliders dims a gap under the largest chroma and shows there the color a pick stores. - Tests cover the blue primary, a dark blue whose runs are far apart, the C track over that gap, and a grid of lightness and hue where no chroma above the one found fits. --- crates/color/src/oklab.rs | 135 ++++++++++++++++-- crates/ui-egui/src/panels/color_wheel.rs | 10 +- .../ui-egui/src/panels/tests_color_wheel.rs | 15 ++ 3 files changed, 146 insertions(+), 14 deletions(-) diff --git a/crates/color/src/oklab.rs b/crates/color/src/oklab.rs index 90467fc6c3..9084c083a4 100644 --- a/crates/color/src/oklab.rs +++ b/crates/color/src/oklab.rs @@ -36,29 +36,105 @@ pub fn in_srgb(rgb: [f64; 3]) -> bool { rgb.iter().all(|v| (-GAMUT_SLACK..=1.0 + GAMUT_SLACK).contains(v)) } +/// The chroma past which no hue at any lightness is inside sRGB. +const CHROMA_SEARCH: f64 = 0.5; + /// The largest chroma sRGB holds at lightness `l` and hue `h°`: 0 at or outside black and white. pub fn max_chroma(l: f64, h: f64) -> f64 { - if !(l > 0.0 && l < 1.0) || !h.is_finite() { + fitting_chroma(l, h, CHROMA_SEARCH) +} + +/// The largest chroma from 0 to `top` (at most [`CHROMA_SEARCH`]) that sRGB holds at lightness `l` +/// and hue `h°`: 0 at or outside black and white. +/// +/// Along a hue at a given lightness each linear sRGB component is a cubic in the chroma, so sRGB can +/// hold more than one run of chroma: near blue a run of low chroma and one ending at the blue +/// primary. A chroma enters or leaves the gamut only where a component's cubic reaches an edge of +/// [`in_srgb`], so the search tests the chromas between those points from the top down and refines +/// the highest run that fits. +fn fitting_chroma(l: f64, h: f64, top: f64) -> f64 { + if !(l > 0.0 && l < 1.0) || !h.is_finite() || top.is_nan() || top <= 0.0 { return 0.0; } - // sRGB holds every chroma from 0 up to its edge along a hue at a given lightness. - let (mut lo, mut hi) = (0.0, 0.5); - for _ in 0..40 { - let mid = (lo + hi) / 2.0; - if in_srgb(oklch_to_srgb(l, mid, h)) { lo = mid } else { hi = mid } + let top = top.min(CHROMA_SEARCH); + let fits = |c: f64| in_srgb(oklch_to_srgb(l, c, h)); + if fits(top) { + return top; } - lo + let decode = |v: f64| if v <= 0.040_45 { v / 12.92 } else { ((v + 0.055) / 1.055).powf(2.4) }; + let linear = |c: f64| oklch_to_srgb(l, c, h).map(decode); + // The edges of `in_srgb` in linear light. + let edges = [decode(-GAMUT_SLACK), decode(1.0 + GAMUT_SLACK)]; + let samples = [0.0, 1.0, 2.0, 3.0].map(linear); + let mut cuts = vec![0.0, top]; + for i in 0..3 { + // The cubic's coefficients from its values at chroma 0, 1, 2 and 3. + let [p0, p1, p2, p3] = samples.map(|s| s[i]); + let d3 = (p3 - 3.0 * p2 + 3.0 * p1 - p0) / 6.0; + let d2 = (p2 - 2.0 * p1 + p0) / 2.0 - 3.0 * d3; + let d1 = p1 - p0 - d2 - d3; + let cubic = |c: f64| ((d3 * c + d2) * c + d1) * c + p0; + // The cubic is monotonic between its turning points, so it reaches each edge at most once + // between two of them. + let mut ends = vec![0.0, top]; + let (a, b) = (3.0 * d3, 2.0 * d2); + if a != 0.0 { + let disc = b * b - 4.0 * a * d1; + if disc >= 0.0 { + let q = disc.sqrt(); + ends.extend([(-b - q) / (2.0 * a), (-b + q) / (2.0 * a)]); + } + } else if b != 0.0 { + ends.push(-d1 / b); + } + ends.retain(|x| (0.0..=top).contains(x)); + ends.sort_by(f64::total_cmp); + cuts.extend_from_slice(&ends); + for w in ends.windows(2) { + for edge in edges { + let (mut lo, mut hi) = (w[0], w[1]); + let below = cubic(lo) < edge; + if below == (cubic(hi) < edge) { + continue; + } + for _ in 0..60 { + let mid = (lo + hi) / 2.0; + if (cubic(mid) < edge) == below { lo = mid } else { hi = mid } + } + cuts.push((lo + hi) / 2.0); + } + } + } + cuts.sort_by(f64::total_cmp); + cuts.dedup(); + let mut tests = Vec::with_capacity(cuts.len() * 2); + for w in cuts.windows(2) { + tests.extend([w[0], (w[0] + w[1]) / 2.0]); + } + tests.push(top); + // `top` does not fit, so the highest test that fits has a test above it that does not. + for w in tests.windows(2).rev() { + if fits(w[0]) { + let (mut lo, mut hi) = (w[0], w[1]); + for _ in 0..40 { + let mid = (lo + hi) / 2.0; + if fits(mid) { lo = mid } else { hi = mid } + } + return lo; + } + } + 0.0 } /// The sRGB color (gamma encoded, 0..=1) of OKLCH `(l, c, h°)`, and whether its chroma was lowered: -/// a color outside sRGB keeps its lightness and hue and takes the largest chroma that fits. +/// a color outside sRGB keeps its lightness and hue and takes the largest chroma under `c` that fits. /// Lightness is clamped to 0..=1 and chroma to 0 or more. pub fn from_oklch(l: f64, c: f64, h: f64) -> ([f32; 3], bool) { let l = if l.is_nan() { 0.0 } else { l.clamp(0.0, 1.0) }; let c = if c.is_nan() { 0.0 } else { c.max(0.0) }; let h = if h.is_finite() { h } else { 0.0 }; let exact = oklch_to_srgb(l, c, h); - let (rgb, lowered) = if in_srgb(exact) { (exact, false) } else { (oklch_to_srgb(l, max_chroma(l, h).min(c), h), true) }; + let (rgb, lowered) = if in_srgb(exact) { (exact, false) } else { (oklch_to_srgb(l, fitting_chroma(l, h, c), h), true) }; (rgb.map(|v| v.clamp(0.0, 1.0) as f32), lowered) } @@ -126,6 +202,47 @@ mod tests { assert!(!from_oklch(l, max * 0.5, h).1); } + /// At blue's lightness and hue sRGB holds a run of low chroma and a run ending at the blue + /// primary, with chromas outside sRGB between them: the largest chroma is the primary's. + #[test] + fn the_largest_chroma_of_blue_is_the_primarys() { + let [l, c, h] = to_oklch([0.0, 0.0, 1.0]); + assert!(!in_srgb(oklch_to_srgb(l, 0.29, h)), "the runs have a gap"); + let max = max_chroma(l, h); + assert!(max >= 0.3132 && max >= c - 1e-6 && in_srgb(oklch_to_srgb(l, max, h)), "{max} {c}"); + assert_eq!(eight(from_oklch(l, CHROMA_FULL, h).0), [0, 0, 255]); + } + + /// A dark blue whose runs are far apart: the largest chroma is the top of the upper run, and a + /// chroma in the gap is lowered to the top of the run under it, keeping lightness and hue. + #[test] + fn a_chroma_between_two_runs_is_lowered_to_the_run_under_it() { + let (l, h) = (0.14, 264.0); + let max = max_chroma(l, h); + assert!(max > 0.097 && in_srgb(oklch_to_srgb(l, max, h)) && !in_srgb(oklch_to_srgb(l, max + 1e-3, h)), "{max}"); + assert!(!in_srgb(oklch_to_srgb(l, 0.09, h)), "0.09 is in the gap"); + let (rgb, lowered) = from_oklch(l, 0.09, h); + let [ol, oc, oh] = to_oklch(rgb); + assert!(lowered && (ol - l).abs() < 1e-3 && (oh - h).abs() < 0.5 && (oc - 0.0825).abs() < 1e-3, "{ol} {oc} {oh}"); + } + + /// Every lightness and hue on a grid: the chroma found fits, and no chroma above it does. + #[test] + fn no_chroma_above_the_largest_fits() { + for li in 1..50 { + let l = f64::from(li) / 50.0; + for hi in 0..120 { + let h = f64::from(hi) * 3.0; + let max = max_chroma(l, h); + assert!(in_srgb(oklch_to_srgb(l, max, h)), "{l} {h} {max}"); + for step in 1..=200 { + let c = max + f64::from(step) * 0.0005; + assert!(!in_srgb(oklch_to_srgb(l, c, h)), "{l} {h}: {max} but {c} fits"); + } + } + } + } + #[test] fn black_white_and_bad_numbers_hold_no_chroma() { assert_eq!(max_chroma(0.0, 30.0), 0.0); diff --git a/crates/ui-egui/src/panels/color_wheel.rs b/crates/ui-egui/src/panels/color_wheel.rs index 2a88a3f54a..2a2a95d7ad 100644 --- a/crates/ui-egui/src/panels/color_wheel.rs +++ b/crates/ui-egui/src/panels/color_wheel.rs @@ -385,14 +385,14 @@ pub(crate) fn remembered_oklch(cms: &Cms, c: &Color, shown: [f32; 3], lch: [f64; } /// The color a track shows at OKLCH `lch`: the color itself inside sRGB, and outside it dimmed. -/// A color outside sRGB shows at the largest chroma that fits at its L and H, the color a pick -/// there stores. With `max_chroma` (the C track, whose L and H stay fixed) that chroma is given; -/// without it, it is found for each color. +/// A color outside sRGB shows at the largest chroma under its own that fits at its L and H, the +/// color a pick there stores. With `max_chroma` (the C track, whose L and H stay fixed) a chroma +/// past it shows at it; a chroma under it can still be outside sRGB, in a gap between two runs of +/// chroma that fit, and is found as without it. pub(crate) fn oklch_track(lch: [f64; 3], max_chroma: Option) -> Color32 { let (rgb, outside) = match max_chroma { Some(m) if lch[1] > m => (oklab::oklch_to_srgb(lch[0], m, lch[2]), true), - Some(_) => (oklab::oklch_to_srgb(lch[0], lch[1], lch[2]), false), - None => { + _ => { let (rgb, lowered) = oklab::from_oklch(lch[0], lch[1], lch[2]); (rgb.map(f64::from), lowered) } diff --git a/crates/ui-egui/src/panels/tests_color_wheel.rs b/crates/ui-egui/src/panels/tests_color_wheel.rs index 407f6ffabe..821ac678bc 100644 --- a/crates/ui-egui/src/panels/tests_color_wheel.rs +++ b/crates/ui-egui/src/panels/tests_color_wheel.rs @@ -695,6 +695,21 @@ fn the_oklch_tracks_dim_the_colors_outside_srgb_and_the_tick_marks_the_largest_c assert_eq!((chroma_tick(0.0), chroma_tick(0.5)), (0.0, 1.0)); } +/// At a dark blue sRGB holds two runs of chroma with a gap between them: the C track dims the gap +/// and shows there the color a pick stores, the top of the run under it. +#[test] +fn the_c_track_dims_a_gap_under_the_largest_chroma() { + use vectorcraft_color::oklab; + let (l, h) = (0.14, 264.0); + let max = oklab::max_chroma(l, h); + assert!(max > 0.09 && !oklab::in_srgb(oklab::oklch_to_srgb(l, 0.09, h)), "0.09 is in the gap under {max}"); + let (stored, lowered) = oklab::from_oklch(l, 0.09, h); + let [r, g, b] = stored.map(|v| (f64::from(v).clamp(0.0, 1.0) * 255.0).round() as u8); + assert!(lowered); + assert_eq!(oklch_track([l, 0.09, h], Some(max)), egui::Color32::from_rgb(r, g, b).gamma_multiply(0.3)); + assert_eq!(oklch_track([l, max, h], Some(max)).a(), 255, "the top of the upper run is inside sRGB"); +} + /// After Edit › Color Settings picks a working RGB space other than sRGB, Panel menu › OKLCH Sliders /// is gray and `ui.colorWheel {sliders: "oklch"}` answers an error; rows already shown are gray. #[test] From 07be8c649645219616bf9ae4e232c4308d09844b Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 17 Nov 2026 22:38:09 -0800 Subject: [PATCH 002/151] Color Wheel: the panel menu's view and channel items run ui.colorWheel Wheel View, Box View and the Box Channel items now run ui.colorWheel through the app's command entry point, as OKLCH Sliders does, and show an error in the status bar. A checked view or channel runs no command. --- crates/ui-egui/src/panels/color_wheel.rs | 21 ++++++++++++------- .../src/panels/tests_color_wheel_box.rs | 9 +++++++- 2 files changed, 22 insertions(+), 8 deletions(-) diff --git a/crates/ui-egui/src/panels/color_wheel.rs b/crates/ui-egui/src/panels/color_wheel.rs index 2a2a95d7ad..4886a04696 100644 --- a/crates/ui-egui/src/panels/color_wheel.rs +++ b/crates/ui-egui/src/panels/color_wheel.rs @@ -176,18 +176,20 @@ pub(crate) fn set(settings: &mut Settings, p: &Value, cms: &Cms) -> Result<(), S } /// The panel menu: Wheel View and Box View, Box Channel while the box shows, and OKLCH Sliders. +/// Each item runs `ui.colorWheel` through the app's command entry point; a checked view or channel +/// runs nothing. pub fn menu(app: &mut VectorcraftApp, ui: &mut Ui) { let set = app.ui.color_wheel.clone(); for (label, view) in [(tl!("Wheel View"), View::Wheel), (tl!("Box View"), View::Box)] { - if menu_item(ui, label, true, set.view == view) { - command(app, &json!({ "view": view.id() })).ok(); + if menu_item(ui, label, true, set.view == view) && set.view != view { + run(app, json!({ "view": view.id() })); } } ui.add_enabled_ui(set.view == View::Box, |ui| { ui.menu_button(format!(" {}", tl!("Box Channel")), |ui| { for ch in Channel::ALL { - if menu_item(ui, ch.name(), true, ch == set.channel) { - command(app, &json!({ "channel": ch.id() })).ok(); + if menu_item(ui, ch.name(), true, ch == set.channel) && ch != set.channel { + run(app, json!({ "channel": ch.id() })); } } }); @@ -198,9 +200,14 @@ pub fn menu(app: &mut VectorcraftApp, ui: &mut Ui) { let enabled = on || cms::active().rgb_is_srgb(); if widgets::menu_item_hint(ui, tl!("OKLCH Sliders"), enabled, on, tl!("OKLCH needs sRGB as the working RGB space")) { let sliders = if on { Sliders::None } else { Sliders::Oklch }; - if let Err(e) = app.run("ui.colorWheel", json!({ "sliders": sliders.id() })) { - app.status(e); - } + run(app, json!({ "sliders": sliders.id() })); + } +} + +/// Run `ui.colorWheel` with `p` from the panel menu, and show an error in the status bar. +fn run(app: &mut VectorcraftApp, p: Value) { + if let Err(e) = app.run("ui.colorWheel", p) { + app.status(e); } } diff --git a/crates/ui-egui/src/panels/tests_color_wheel_box.rs b/crates/ui-egui/src/panels/tests_color_wheel_box.rs index 2e0e6ae1a5..00eac74e97 100644 --- a/crates/ui-egui/src/panels/tests_color_wheel_box.rs +++ b/crates/ui-egui/src/panels/tests_color_wheel_box.rs @@ -300,7 +300,7 @@ fn the_settings_are_kept_and_read_leniently() { } /// The panel menu lists Wheel View and Box View with the shown one checked, and Box Channel; its -/// items set the view and the channel. +/// items set the view and the channel through the app's command entry point. #[test] fn the_panel_menu_switches_the_view_and_the_channel() { let mut app = app(json!("#ff0000"), "hue"); @@ -320,10 +320,17 @@ fn the_panel_menu_switches_the_view_and_the_channel() { ); h.run_steps(3); assert!(h.query_by_label("✓ Wheel View").is_some()); + let commands = h.state().run_count; h.get_by_label(" Box View").click(); h.run_steps(2); assert_eq!(h.state().ui.color_wheel.view, View::Box); + assert_eq!(h.state().run_count, commands.wrapping_add(1), "Box View runs one ui.colorWheel command"); assert!(h.query_by_label("✓ Box View").is_some()); + // The checked item runs nothing. + h.get_by_label("✓ Box View").click(); + h.run_steps(2); + assert_eq!(h.state().run_count, commands.wrapping_add(1), "the checked Box View runs no command"); + assert_eq!(h.state().ui.color_wheel.view, View::Box); } /// Every channel's box puts each color back where it reads it, and the strip's value is the From f55a779aba78e2781aa77d344f72fbe41cc4d0e8 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 18 Nov 2026 01:08:19 -0800 Subject: [PATCH 003/151] i18n: Gujarati translates the ui.colorWheel sliders errors The `sliders` value error and the OKLCH working-space error get Gujarati @msg rows, as the other catalogs have, with a test that checks every catalog keeps the accepted values. --- crates/ui-egui/src/i18n/gu.tsv | 2 ++ crates/ui-egui/src/panels/tests_color_wheel.rs | 18 ++++++++++++++++++ 2 files changed, 20 insertions(+) diff --git a/crates/ui-egui/src/i18n/gu.tsv b/crates/ui-egui/src/i18n/gu.tsv index e0510bceeb..aa999ef649 100644 --- a/crates/ui-egui/src/i18n/gu.tsv +++ b/crates/ui-egui/src/i18n/gu.tsv @@ -1954,6 +1954,8 @@ Chroma ક્રોમા The largest chroma sRGB holds at this lightness and hue આ લાઇટનેસ અને હ્યૂ પર sRGB સમાવી શકે તે સૌથી વધુ ક્રોમા OKLCH needs sRGB as the working RGB space OKLCH માટે કાર્યકારી RGB સ્પેસ તરીકે sRGB જરૂરી છે +@msg `sliders` must be none or oklch `sliders` none અથવા oklch હોવું જોઈએ +@msg OKLCH needs sRGB as the working RGB space OKLCH માટે કાર્યકારી RGB સ્પેસ તરીકે sRGB જરૂરી છે Lightness લાઇટનેસ Lab Spot Colors: Lab સ્પોટ રંગો: Landscape લેન્ડસ્કેપ diff --git a/crates/ui-egui/src/panels/tests_color_wheel.rs b/crates/ui-egui/src/panels/tests_color_wheel.rs index 821ac678bc..48cf4e9e29 100644 --- a/crates/ui-egui/src/panels/tests_color_wheel.rs +++ b/crates/ui-egui/src/panels/tests_color_wheel.rs @@ -861,3 +861,21 @@ fn ui_color_wheel_sets_and_reads_the_sliders() { assert_eq!(e, "`sliders` must be none or oklch"); assert_eq!(app.ui.color_wheel.view, crate::panels::color_wheel::View::Box, "an error changes nothing"); } + +/// The `sliders` errors are translated in every catalog, and each translation keeps the accepted +/// values. +#[test] +fn ui_color_wheel_sliders_errors_are_translated() { + let errors = [("`sliders` must be none or oklch", &["none", "oklch"][..]), ("OKLCH needs sRGB as the working RGB space", &["OKLCH", "sRGB"][..])]; + for code in [ + "bg", "bs", "ca", "cs", "da", "de", "el", "es", "fi", "fr", "gu", "hi", "hu", "id", "it", "ja", "ka", "ko", "nl", "pl", "pt-br", "ru", "sv", "tr", + "uk", "vi", "zh-hans", "zh-hant", + ] { + let lang = crate::i18n::Lang::from_code(code).expect("registered"); + for (error, values) in errors { + let shown = crate::i18n::message(lang, error); + assert_ne!(shown, error, "{code}"); + assert!(values.iter().all(|v| shown.contains(v)), "{code}: {shown}"); + } + } +} From 189720d39798a7eb1f56c02f277e7dc5550bc178 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 18 Nov 2026 01:29:45 -0800 Subject: [PATCH 004/151] Tests: format the Color Wheel sliders translation test --- crates/ui-egui/src/panels/tests_color_wheel.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/crates/ui-egui/src/panels/tests_color_wheel.rs b/crates/ui-egui/src/panels/tests_color_wheel.rs index 48cf4e9e29..b0efcd4b00 100644 --- a/crates/ui-egui/src/panels/tests_color_wheel.rs +++ b/crates/ui-egui/src/panels/tests_color_wheel.rs @@ -868,8 +868,8 @@ fn ui_color_wheel_sets_and_reads_the_sliders() { fn ui_color_wheel_sliders_errors_are_translated() { let errors = [("`sliders` must be none or oklch", &["none", "oklch"][..]), ("OKLCH needs sRGB as the working RGB space", &["OKLCH", "sRGB"][..])]; for code in [ - "bg", "bs", "ca", "cs", "da", "de", "el", "es", "fi", "fr", "gu", "hi", "hu", "id", "it", "ja", "ka", "ko", "nl", "pl", "pt-br", "ru", "sv", "tr", - "uk", "vi", "zh-hans", "zh-hant", + "bg", "bs", "ca", "cs", "da", "de", "el", "es", "fi", "fr", "gu", "hi", "hu", "id", "it", "ja", "ka", "ko", "nl", "pl", "pt-br", "ru", "sv", + "tr", "uk", "vi", "zh-hans", "zh-hant", ] { let lang = crate::i18n::Lang::from_code(code).expect("registered"); for (error, values) in errors { From 00322ad70f343e315ae5d879f1e5b170094bf533 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 19 Nov 2026 11:27:47 -0800 Subject: [PATCH 005/151] Color Wheel: OKLCH lightness endpoints give exact black and white from_oklch returns exactly black at lightness 0 and exactly white at lightness 1, as CSS Color 4 specifies, and reports a positive chroma there as lowered. The gamut tolerance no longer leaves a positive red channel at L=0. The command text and docs say a color outside sRGB takes the largest chroma that fits at or below the one asked for, that color.convert measures the stored color's display sRGB, and that a null key keeps its value. The saved-settings test also checks that an unknown slider value keeps the saved view. --- crates/color/src/oklab.rs | 17 ++++++++++++++++- crates/mcp/src/ui_catalog.rs | 2 +- crates/ui-egui/src/menus/ui_commands.rs | 2 +- crates/ui-egui/src/panels/tests_color_wheel.rs | 14 ++++++++------ docs/mcp.md | 2 +- docs/target-app-parity.md | 2 +- 6 files changed, 28 insertions(+), 11 deletions(-) diff --git a/crates/color/src/oklab.rs b/crates/color/src/oklab.rs index 31500d1ac5..7deb757f58 100644 --- a/crates/color/src/oklab.rs +++ b/crates/color/src/oklab.rs @@ -113,11 +113,16 @@ fn turning_points(a: f64, b: f64, c: f64) -> Vec { /// The sRGB color (gamma encoded, 0..=1) of OKLCH `(l, c, h°)`, and whether its chroma was lowered: /// a color outside sRGB keeps its lightness and hue and takes the largest chroma below it that -/// fits. Lightness is clamped to 0..=1 and chroma to 0 or more. +/// fits. Lightness is clamped to 0..=1 and chroma to 0 or more. Lightness 0 gives exactly black and +/// lightness 1 exactly white, as CSS Color 4 specifies, and a positive chroma there counts as +/// lowered. pub fn from_oklch(l: f64, c: f64, h: f64) -> ([f32; 3], bool) { let l = if l.is_nan() { 0.0 } else { l.clamp(0.0, 1.0) }; let c = if c.is_nan() { 0.0 } else { c.max(0.0) }; let h = if h.is_finite() { h } else { 0.0 }; + if l == 0.0 || l == 1.0 { + return ([l as f32; 3], c > 0.0); + } let exact = oklch_to_srgb(l, c, h); let (rgb, lowered) = if in_srgb(exact) { (exact, false) } else { (oklch_to_srgb(l, largest_fitting_chroma(l, h, c), h), true) }; (rgb.map(|v| v.clamp(0.0, 1.0) as f32), lowered) @@ -263,4 +268,14 @@ mod tests { assert_eq!(eight(from_oklch(f64::NAN, f64::NAN, f64::NAN).0), [0, 0, 0]); assert_eq!(eight(from_oklch(2.0, -1.0, 0.0).0), [255, 255, 255]); } + + /// The lightness endpoints give exactly black and white at any chroma and hue, and report a + /// positive chroma as lowered. A rounded 8-bit comparison would hide a small leftover channel. + #[test] + fn the_lightness_endpoints_give_exact_black_and_white() { + assert_eq!(from_oklch(0.0, 0.04, 0.0), ([0.0; 3], true)); + assert_eq!(from_oklch(0.0, 0.0, 120.0), ([0.0; 3], false)); + assert_eq!(from_oklch(1.0, 0.1, 250.0), ([1.0; 3], true)); + assert_eq!(from_oklch(1.0, 0.0, 0.0), ([1.0; 3], false)); + } } diff --git a/crates/mcp/src/ui_catalog.rs b/crates/mcp/src/ui_catalog.rs index 290623b48b..6e8e1e3426 100644 --- a/crates/mcp/src/ui_catalog.rs +++ b/crates/mcp/src/ui_catalog.rs @@ -1573,7 +1573,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "ui.colorWheel", "Color Wheel Options", "", - "{view?: wheel|box, channel?: hue|saturation|brightness|red|green|blue, sliders?: none|oklch|hsl, harmony?: bool, harmonyRule?: complementary|splitComplementary|leftComplement|rightComplement|analogous|analogous2|triad|tetrad|tetrad2|tetrad3|compound|compound2|highContrast|highContrast3|pentagram, vision?: bool} show the Color Wheel panel's wheel or its box, as the panel menu's Wheel View and Box View do, pick the box's channel, as Box Channel does, and show no slider rows under the wheel or the box (none), OKLCH Sliders (oklch) or HSL Sliders (hsl), as the menu items of those names do: the box is a color field with the channel's strip at its right, and the field shows the other two components (hue: saturation across and brightness up; saturation: hue across and brightness up; brightness: hue across and saturation up; red: blue across and green up; green: blue across and red up; blue: red across and green up); OKLCH Sliders edit lightness 0 to 100 %, chroma 0 to 100 % of 0.4 and hue 0 to 360°, CSS Color 4's OKLCH of the display sRGB, and a color outside sRGB keeps L and H and takes the largest chroma that fits; HSL Sliders edit hue 0 to 360°, saturation 0 to 100 % and lightness 0 to 100 %, CSS Color 4's HSL of the display sRGB; harmony shows a marker on the wheel's ring for each other color of harmonyRule (the Color Guide's rule of that id; a rule's label is taken too), as Show Harmony and Harmony Rule do, and a click on a marker applies its color; vision shows Show Color Vision Preview's row under the wheel or the box, four chips with the current color as simulated for protanopia, deuteranopia and tritanopia (the simulations of view.proofSetup's protanopia, deuteranopia and tritanopia targets) and for achromatopsia (the gray with the color's CIE L*), each named with its hex value in its tooltip and to screen readers, and taking the keyboard focus; a click or a key on a chip does not apply its color; keys left out or null keep their values ({} reads them), params that are not an object, another key or a value off the list are an error and change nothing, oklch is an error while the working RGB space is not sRGB, the settings are kept with the preferences, and the command does not open the panel (window.panel {panel: \"colorWheel\"} does) (ui.inspect: ui.color_wheel) → {view, channel, sliders, harmony, harmonyRule, vision}", + "{view?: wheel|box, channel?: hue|saturation|brightness|red|green|blue, sliders?: none|oklch|hsl, harmony?: bool, harmonyRule?: complementary|splitComplementary|leftComplement|rightComplement|analogous|analogous2|triad|tetrad|tetrad2|tetrad3|compound|compound2|highContrast|highContrast3|pentagram, vision?: bool} show the Color Wheel panel's wheel or its box, as the panel menu's Wheel View and Box View do, pick the box's channel, as Box Channel does, and show no slider rows under the wheel or the box (none), OKLCH Sliders (oklch) or HSL Sliders (hsl), as the menu items of those names do: the box is a color field with the channel's strip at its right, and the field shows the other two components (hue: saturation across and brightness up; saturation: hue across and brightness up; brightness: hue across and saturation up; red: blue across and green up; green: blue across and red up; blue: red across and green up); OKLCH Sliders edit lightness 0 to 100 %, chroma 0 to 100 % of 0.4 and hue 0 to 360°, CSS Color 4's OKLCH of the display sRGB, and a color outside sRGB keeps L and H and takes the largest chroma that fits at or below the one asked for; HSL Sliders edit hue 0 to 360°, saturation 0 to 100 % and lightness 0 to 100 %, CSS Color 4's HSL of the display sRGB; harmony shows a marker on the wheel's ring for each other color of harmonyRule (the Color Guide's rule of that id; a rule's label is taken too), as Show Harmony and Harmony Rule do, and a click on a marker applies its color; vision shows Show Color Vision Preview's row under the wheel or the box, four chips with the current color as simulated for protanopia, deuteranopia and tritanopia (the simulations of view.proofSetup's protanopia, deuteranopia and tritanopia targets) and for achromatopsia (the gray with the color's CIE L*), each named with its hex value in its tooltip and to screen readers, and taking the keyboard focus; a click or a key on a chip does not apply its color; keys left out or null keep their values ({} reads them), params that are not an object, another key or a value off the list are an error and change nothing, oklch is an error while the working RGB space is not sRGB, the settings are kept with the preferences, and the command does not open the panel (window.panel {panel: \"colorWheel\"} does) (ui.inspect: ui.color_wheel) → {view, channel, sliders, harmony, harmonyRule, vision}", ), ( "ui.savePdfDialog", diff --git a/crates/ui-egui/src/menus/ui_commands.rs b/crates/ui-egui/src/menus/ui_commands.rs index ef7975b9a0..7ab1ff88b8 100644 --- a/crates/ui-egui/src/menus/ui_commands.rs +++ b/crates/ui-egui/src/menus/ui_commands.rs @@ -1574,7 +1574,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "ui.colorWheel", "Color Wheel Options", "", - "{view?: wheel|box, channel?: hue|saturation|brightness|red|green|blue, sliders?: none|oklch|hsl, harmony?: bool, harmonyRule?: complementary|splitComplementary|leftComplement|rightComplement|analogous|analogous2|triad|tetrad|tetrad2|tetrad3|compound|compound2|highContrast|highContrast3|pentagram, vision?: bool} show the Color Wheel panel's wheel or its box, as the panel menu's Wheel View and Box View do, pick the box's channel, as Box Channel does, and show no slider rows under the wheel or the box (none), OKLCH Sliders (oklch) or HSL Sliders (hsl), as the menu items of those names do: the box is a color field with the channel's strip at its right, and the field shows the other two components (hue: saturation across and brightness up; saturation: hue across and brightness up; brightness: hue across and saturation up; red: blue across and green up; green: blue across and red up; blue: red across and green up); OKLCH Sliders edit lightness 0 to 100 %, chroma 0 to 100 % of 0.4 and hue 0 to 360°, CSS Color 4's OKLCH of the display sRGB, and a color outside sRGB keeps L and H and takes the largest chroma that fits; HSL Sliders edit hue 0 to 360°, saturation 0 to 100 % and lightness 0 to 100 %, CSS Color 4's HSL of the display sRGB; harmony shows a marker on the wheel's ring for each other color of harmonyRule (the Color Guide's rule of that id; a rule's label is taken too), as Show Harmony and Harmony Rule do, and a click on a marker applies its color; vision shows Show Color Vision Preview's row under the wheel or the box, four chips with the current color as simulated for protanopia, deuteranopia and tritanopia (the simulations of view.proofSetup's protanopia, deuteranopia and tritanopia targets) and for achromatopsia (the gray with the color's CIE L*), each named with its hex value in its tooltip and to screen readers, and taking the keyboard focus; a click or a key on a chip does not apply its color; keys left out or null keep their values ({} reads them), params that are not an object, another key or a value off the list are an error and change nothing, oklch is an error while the working RGB space is not sRGB, the settings are kept with the preferences, and the command does not open the panel (window.panel {panel: \"colorWheel\"} does) (ui.inspect: ui.color_wheel) → {view, channel, sliders, harmony, harmonyRule, vision}", + "{view?: wheel|box, channel?: hue|saturation|brightness|red|green|blue, sliders?: none|oklch|hsl, harmony?: bool, harmonyRule?: complementary|splitComplementary|leftComplement|rightComplement|analogous|analogous2|triad|tetrad|tetrad2|tetrad3|compound|compound2|highContrast|highContrast3|pentagram, vision?: bool} show the Color Wheel panel's wheel or its box, as the panel menu's Wheel View and Box View do, pick the box's channel, as Box Channel does, and show no slider rows under the wheel or the box (none), OKLCH Sliders (oklch) or HSL Sliders (hsl), as the menu items of those names do: the box is a color field with the channel's strip at its right, and the field shows the other two components (hue: saturation across and brightness up; saturation: hue across and brightness up; brightness: hue across and saturation up; red: blue across and green up; green: blue across and red up; blue: red across and green up); OKLCH Sliders edit lightness 0 to 100 %, chroma 0 to 100 % of 0.4 and hue 0 to 360°, CSS Color 4's OKLCH of the display sRGB, and a color outside sRGB keeps L and H and takes the largest chroma that fits at or below the one asked for; HSL Sliders edit hue 0 to 360°, saturation 0 to 100 % and lightness 0 to 100 %, CSS Color 4's HSL of the display sRGB; harmony shows a marker on the wheel's ring for each other color of harmonyRule (the Color Guide's rule of that id; a rule's label is taken too), as Show Harmony and Harmony Rule do, and a click on a marker applies its color; vision shows Show Color Vision Preview's row under the wheel or the box, four chips with the current color as simulated for protanopia, deuteranopia and tritanopia (the simulations of view.proofSetup's protanopia, deuteranopia and tritanopia targets) and for achromatopsia (the gray with the color's CIE L*), each named with its hex value in its tooltip and to screen readers, and taking the keyboard focus; a click or a key on a chip does not apply its color; keys left out or null keep their values ({} reads them), params that are not an object, another key or a value off the list are an error and change nothing, oklch is an error while the working RGB space is not sRGB, the settings are kept with the preferences, and the command does not open the panel (window.panel {panel: \"colorWheel\"} does) (ui.inspect: ui.color_wheel) → {view, channel, sliders, harmony, harmonyRule, vision}", ), ( "ui.savePdfDialog", diff --git a/crates/ui-egui/src/panels/tests_color_wheel.rs b/crates/ui-egui/src/panels/tests_color_wheel.rs index 99f7cd97ea..343cd9f8c6 100644 --- a/crates/ui-egui/src/panels/tests_color_wheel.rs +++ b/crates/ui-egui/src/panels/tests_color_wheel.rs @@ -1066,15 +1066,17 @@ fn the_remembered_hsl_follows_a_change_of_working_space() { fn saved_color_wheel_settings_are_read_leniently() { let mut saved = serde_json::to_value(crate::UiState::default()).unwrap(); saved["color_rgb_percent"] = json!(true); - for (value, sliders) in [ - (json!({"sliders": "oklch"}), Sliders::Oklch), - (json!({"sliders": "hsl"}), Sliders::Hsl), - (json!({"sliders": "hwb", "view": "box"}), Sliders::None), - (json!(5), Sliders::None), + let wheel = crate::panels::color_wheel::View::Wheel; + let box_view = crate::panels::color_wheel::View::Box; + for (value, sliders, view) in [ + (json!({"sliders": "oklch"}), Sliders::Oklch, wheel), + (json!({"sliders": "hsl"}), Sliders::Hsl, wheel), + (json!({"sliders": "hwb", "view": "box"}), Sliders::None, box_view), + (json!(5), Sliders::None, wheel), ] { saved["color_wheel"] = value.clone(); let ui: crate::UiState = serde_json::from_value(saved.clone()).unwrap(); - assert_eq!((ui.color_wheel.sliders, ui.color_rgb_percent), (sliders, true), "{value}"); + assert_eq!((ui.color_wheel.sliders, ui.color_wheel.view, ui.color_rgb_percent), (sliders, view, true), "{value}"); } } diff --git a/docs/mcp.md b/docs/mcp.md index 2debb5d7fc..776c1b30f0 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -686,7 +686,7 @@ strip at its right) in place of the wheel, as the panel menu's Box View and Box shows the wheel again. `{"harmony": true, "harmonyRule": "triad"}` puts a marker on the wheel's ring for each other color of a Color Guide harmony rule, as Show Harmony and Harmony Rule do; the wheel takes the 15 rules whose colors each have a hue of their own (not `monochromatic`, `shades`, `complementary2`, `triad2`, `triad3` or -`highContrast2`). Keys left out keep their values. Params that are not an object, another key or a value off +`highContrast2`). Keys left out or `null` keep their values. Params that are not an object, another key or a value off the list return an error and change nothing. The command returns `{view, channel, sliders, harmony, harmonyRule, vision}`, and the settings are kept with the preferences. diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 8fd9808c6f..364b1f1e3b 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1947,7 +1947,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Colorized images (#1466):** a fill color applied to a selected grayscale or 1-bit image (`paint.setFill`) colorizes it with black, white, a process color or a spot color, and refuses a process color when the image has an alpha channel ([Convert color modes](https://web.archive.org/web/20251220223850/https://helpx.adobe.com/illustrator/desktop/manage-colors/select-and-adjust-colors/convert-color-modes.html), "Colorize Grayscale or 1-bit images"); black and white are accepted there too. The canvas draws each pixel in the color as far as the pixel is dark, with white pixels transparent; PDF export writes the image in the color (a spot color as its ink, Registration in every ink) with the image as its soft mask; Separations Preview and printed separations show it on its color's plates; native files keep the color. EPS and SVG write the image's own pixels. - **Missing library files:** a persistent swatch or graphic style library panel whose file is gone at startup reopens and stays in the preferences, showing the file's path with Locate Library… (`ui.libraryPanel.locate`), which reads the file from where it is now into the same panel. - **Swatch library and Recolor Artwork parameters:** the `swatch.library.*` commands, `swatch.resetDefaults`, the graphic style library save, load and add, the `recolor.*` commands and `color.harmony`'s `limitTo` refuse parameters of the wrong form, such as `names: "Grays"`, `limitTo: 5` or `includeImages: "false"`. Errors name the parameter, except that a `limitTo` that is not a string, such as `5`, gets an unknown-library error. A `null` counts as left out except for `recolor.apply`'s `model`, which must be a string when given. - - **OKLCH Sliders (Color Wheel panel):** as VectorCraft's own addition, the Color Wheel panel's menu item OKLCH Sliders (`ui.colorWheel {sliders: "oklch"}`, kept with the preferences) shows L, C and H rows under the wheel or the box that edit the color by the OKLCH lightness (0 to 100 %), chroma (0 to 100 % of 0.4) and hue (0 to 360°) of its display sRGB, as CSS Color 4 defines them (https://www.w3.org/TR/css-color-4/#specifying-oklab-oklch). Each track dims the colors outside sRGB, and a tick on the C track marks the largest chroma sRGB holds at the row's L and H; a color outside sRGB keeps L and H and takes the largest chroma that fits, and the C row keeps the chroma asked for. The rows take the arrow keys after a click and report their names, values, ranges and adjust actions to screen readers. While the active document's RGB space (its assigned profile, else the working RGB space of Edit › Color Settings) is not sRGB, the unchecked item is gray and `ui.colorWheel {sliders: "oklch"}` answers an error; rows shown before the space changed are gray, and the checked item still hides them. `color.convert {color, to: "oklch"}` answers the same L, C and H for a color inside sRGB. For a color outside sRGB, it clips the display RGB to 0 to 1 first, so its L, C and H can differ from the rows' values. Evidence: `crates/color/src/oklab.rs` tests; `convert_to_oklch_answers_lightness_chroma_and_hue` in `crates/engine/src/tests/colormgmt.rs`; the OKLCH tests in `crates/ui-egui/src/panels/tests_color_wheel.rs`, `the_oklch_tracks_dim_the_colors_outside_srgb_and_the_tick_marks_the_largest_chroma` and `oklch_sliders_are_gray_after_the_working_space_changes` among them. Scores and estimates are unchanged. + - **OKLCH Sliders (Color Wheel panel):** as VectorCraft's own addition, the Color Wheel panel's menu item OKLCH Sliders (`ui.colorWheel {sliders: "oklch"}`, kept with the preferences) shows L, C and H rows under the wheel or the box that edit the color by the OKLCH lightness (0 to 100 %), chroma (0 to 100 % of 0.4) and hue (0 to 360°) of its display sRGB, as CSS Color 4 defines them (https://www.w3.org/TR/css-color-4/#specifying-oklab-oklch). Each track dims the colors outside sRGB, and a tick on the C track marks the largest chroma sRGB holds at the row's L and H; a color outside sRGB keeps L and H and takes the largest chroma that fits at or below the one asked for, and the C row keeps the chroma asked for. At lightness 0 and 100 % the color is exactly black and white. The rows take the arrow keys after a click and report their names, values, ranges and adjust actions to screen readers. While the active document's RGB space (its assigned profile, else the working RGB space of Edit › Color Settings) is not sRGB, the unchecked item is gray and `ui.colorWheel {sliders: "oklch"}` answers an error; rows shown before the space changed are gray, and the checked item still hides them. `color.convert {color, to: "oklch"}` answers the same L, C and H for a color inside sRGB. For a color outside sRGB, it clips the display RGB to 0 to 1 first, so its L, C and H can differ from the rows' values. It always measures the display sRGB of the color stored in the document, so after a pick whose chroma did not fit, its C is the chroma that fit and not the value the C row keeps. Evidence: `crates/color/src/oklab.rs` tests; `convert_to_oklch_answers_lightness_chroma_and_hue` in `crates/engine/src/tests/colormgmt.rs`; the OKLCH tests in `crates/ui-egui/src/panels/tests_color_wheel.rs`, `the_oklch_tracks_dim_the_colors_outside_srgb_and_the_tick_marks_the_largest_chroma` and `oklch_sliders_are_gray_after_the_working_space_changes` among them. Scores and estimates are unchanged. - **HSL Sliders (Color Wheel panel):** as VectorCraft's own addition, the Color Wheel panel's menu item HSL Sliders (`ui.colorWheel {sliders: "hsl"}`, kept with the preferences) shows H, S and L rows in place of OKLCH Sliders that edit the color by the hue (0 to 360°), saturation and lightness (0 to 100 %) of its display sRGB, as CSS Color 4 defines HSL (https://www.w3.org/TR/css-color-4/#the-hsl-notation). A pick goes from display sRGB into the working RGB space as the wheel's picks do, and the rows keep the hue of a gray. The rows take the arrow keys after a click and report their names, values, ranges and adjust actions to screen readers. Evidence: `hsl_follows_css_color_4` and `hsl_roundtrip` in `crates/color/src/lib.rs`; the HSL tests in `crates/ui-egui/src/panels/tests_color_wheel.rs`, `a_gray_keeps_the_hsl_hue_it_was_given` among them. Scores and estimates are unchanged. - **Color Wheel panel (part of #978):** Window › Color Wheel shows the Fill and Stroke proxy beside a hue ring around a square with saturation across and brightness up. It edits what the Color panel's sliders edit (the active proxy's color, the selected gradient stop or freeform point) through the same paint commands, and a drag is one undo step. Alt paints the other proxy, and Shift steps the ring by 45°. A pick goes from display sRGB into the working RGB space; an RGB, CMYK or Lab color keeps its model, and a Gray color or a tint of a global swatch becomes a process color in the document's color mode. A click gives the ring or the square the keyboard focus, and the arrow keys then step the color; both report their names and values to screen readers, and the Color Picker's color field takes the same keys. The panel menu's Box View puts a box in the wheel's place: a color field with a channel strip at its right for Hue, Saturation, Brightness, Red, Green or Blue (Box Channel), on the Color Picker's axes, kept with the preferences (`ui.colorWheel`); the strip and the Color Picker's channel slider take the arrow keys after a click. The panel menu's Show Harmony marks the other colors of a harmony rule (Harmony Rule) on the ring; the markers follow the current color, and a click on a marker applies its color (`ui.colorWheel {harmony, harmonyRule}`). Scores and estimates are unchanged. - **Colour:** a Color Picker (colour field, H/S/B/R/G/B channel slider, HSB/RGB/Lab/CMYK fields, hex, web-only snapping, out-of-gamut correction); the Color panel shows a selected colour in its own model and, with nothing selected, the new-art defaults in the mode picked last, which it keeps between sessions; Alt-click paints the other proxy; proxies look through groups and show "?" for mixed paint; Invert, Complement, Apply Last Color (`,`) and Apply Last Gradient (`.`) keep the colour model; every paint command feeds the recent colours. The Color Guide has 21 harmony rules, Steps and Variation options and Limit to Library. Adjust Color Balance (its Global mode shifts tints) and Saturate preview live; Edit Colors and Recolor also reach meshes, images and patterns. Recolor Artwork has colour reduction, five recolour methods, presets, Limit to Library, a colour-wheel Edit tab and Edit Color Group; a local Color Themes panel saves five-colour themes. Fill/Stroke chips open swatch and mixer popovers (the Properties panel has the Control bar's Fill and Stroke chips, Stroke link and weight spinner, with nothing selected too), panels have Illustrator's Window menu keys (Align Shift+F7, Transform Shift+F8, Pathfinder Cmd+Shift+F9, Layers F7, Character Cmd+T…; every panel can be given one in Edit › Keyboard Shortcuts), and Eyedropper Options pick up and apply chosen attributes (Alt and Shift+Alt, image pixels). An ICC CMYK profile converts straight into the RGB working space (not through sRGB, so a wider space such as Wide Gamut RGB keeps colours sRGB can't hold) with the colour settings' black-point compensation, on the canvas and in RGB exports alike (the built-in Generic CMYK compensates both ways, so RGB black separated to a rich black displays as black again). Fills and strokes can overprint (Attributes panel, Overprint Black options), and CMYK documents blend in inks on screen, in PDF and when flattening. Document Color Mode converts the art, symbols, pattern tiles and swatches through the colour settings: Gray stays Gray, RGB grays separate into light grays in cyan, magenta and yellow only, darker four-color grays and a rich black, or go on the black plate only with `grays: "black"` (also for `document.open {colorMode}`). From ae34cc3e770ae680860cbe326d03cc91918eeebd Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 19 Nov 2026 17:00:33 -0800 Subject: [PATCH 006/151] Color Wheel: Show Out-of-Gamut Colors runs through the panel menu's command helper The item called the command function directly, so it skipped the app's command entry point and an error went unreported. It now uses the same helper as the other panel menu items. The menu test checks that one command runs. --- crates/ui-egui/src/panels/color_wheel.rs | 2 +- crates/ui-egui/src/panels/tests_color_wheel_gamut.rs | 2 ++ 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/crates/ui-egui/src/panels/color_wheel.rs b/crates/ui-egui/src/panels/color_wheel.rs index 84415d89ca..0e3df51203 100644 --- a/crates/ui-egui/src/panels/color_wheel.rs +++ b/crates/ui-egui/src/panels/color_wheel.rs @@ -318,7 +318,7 @@ pub fn menu(app: &mut VectorcraftApp, ui: &mut Ui) { }); ui.separator(); if menu_item(ui, tl!("Show Out-of-Gamut Colors"), true, set.gamut) { - command(app, &json!({ "gamut": !set.gamut })).ok(); + run(app, json!({ "gamut": !set.gamut })); } let on = set.sliders == Sliders::Hsl; if menu_item(ui, tl!("HSL Sliders"), true, on) { diff --git a/crates/ui-egui/src/panels/tests_color_wheel_gamut.rs b/crates/ui-egui/src/panels/tests_color_wheel_gamut.rs index da47fa684e..450d9b592e 100644 --- a/crates/ui-egui/src/panels/tests_color_wheel_gamut.rs +++ b/crates/ui-egui/src/panels/tests_color_wheel_gamut.rs @@ -214,9 +214,11 @@ fn the_panel_menu_switches_the_shading() { app, ); h.run_steps(3); + let commands = h.state().run_count; h.get_by_label(" Show Out-of-Gamut Colors").click(); h.run_steps(2); assert!(h.state().ui.color_wheel.gamut); + assert_eq!(h.state().run_count, commands.wrapping_add(1), "the item runs one ui.colorWheel command"); assert!(h.query_by_label("✓ Show Out-of-Gamut Colors").is_some()); h.get_by_label("✓ Show Out-of-Gamut Colors").click(); h.run_steps(2); From 83d84dedcac210aed3d0e794b93f315812b2156e Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 19 Nov 2026 17:13:57 -0800 Subject: [PATCH 007/151] Color Wheel: the checked Harmony Rule item runs no command Clicking the rule that is already set ran ui.colorWheel and counted as a command. It now does nothing, as the checked view and channel items do. --- crates/ui-egui/src/panels/color_wheel.rs | 2 +- crates/ui-egui/src/panels/tests_color_wheel_harmony.rs | 9 +++++++++ 2 files changed, 10 insertions(+), 1 deletion(-) diff --git a/crates/ui-egui/src/panels/color_wheel.rs b/crates/ui-egui/src/panels/color_wheel.rs index 0e3df51203..c34946387c 100644 --- a/crates/ui-egui/src/panels/color_wheel.rs +++ b/crates/ui-egui/src/panels/color_wheel.rs @@ -338,7 +338,7 @@ pub fn menu(app: &mut VectorcraftApp, ui: &mut Ui) { ui.add_enabled_ui(set.view == View::Wheel, |ui| { ui.menu_button(format!(" {}", tl!("Harmony Rule")), |ui| { for rule in harmony_rules() { - if menu_item(ui, rule.label(), true, rule == set.harmony_rule) { + if menu_item(ui, rule.label(), true, rule == set.harmony_rule) && rule != set.harmony_rule { run(app, json!({ "harmonyRule": rule.id() })); } } diff --git a/crates/ui-egui/src/panels/tests_color_wheel_harmony.rs b/crates/ui-egui/src/panels/tests_color_wheel_harmony.rs index 454e43ec49..f7ce477b98 100644 --- a/crates/ui-egui/src/panels/tests_color_wheel_harmony.rs +++ b/crates/ui-egui/src/panels/tests_color_wheel_harmony.rs @@ -344,6 +344,15 @@ fn the_panel_menu_shows_the_harmony_and_picks_the_rule() { h.get_by_label(" Pentagram").click(); h.run_steps(2); assert_eq!(h.state().ui.color_wheel.harmony_rule, Harmony::Pentagram); + // The checked rule runs no command. + if h.query_by_label("✓ Pentagram").is_none() { + h.get_by_label(" Harmony Rule").click(); + h.run_steps(2); + } + let commands = h.state().run_count; + h.get_by_label("✓ Pentagram").click(); + h.run_steps(2); + assert_eq!(h.state().run_count, commands, "the checked rule runs no command"); h.state_mut().run("ui.colorWheel", json!({"view": "box"})).unwrap(); h.run_steps(2); assert!(h.get_by_label("✓ Show Harmony").accesskit_node().data().is_disabled(), "gray while the box shows"); From 2d3be0f51474242f2c6fc8acd7debb57cce86220 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 19 Nov 2026 17:19:01 -0800 Subject: [PATCH 008/151] Pen: Quick Pen drags move a selected path's anchors and segments, and its context menu deletes With no path being drawn, the Quick Pen tool edits the selected paths, as the help page describes ("Drag the anchor points or the path to edit the object", and right-click Delete to remove a path): - A drag on an anchor moves it, and a drag that starts on one of several selected anchors moves them all; a drag on a segment moves its two ends. The tool selects what it moves (select.anchors or select.segments) and sends path.moveAnchors with interpolate, one undo step per drag, so a segment with one moved end is turned and scaled to its new ends: a line stays a line and an arc an arc of the same angle. A dragged anchor snaps to Smart Guides. Escape during the drag takes it back. - A click on an anchor selects it alone, and Shift-click adds it to the selected anchors or takes it out. A click on an open end still goes on drawing from it (with the path selected whole again), a drag there moves the end, and a click on a segment starts a new path. - With the Quick Pen chosen, the canvas context menu has Delete (edit.clear), which removes the selected anchors or objects. The cursor shows what a press does over an anchor, a selected anchor, an open end or a segment. While a path is being drawn, a press adds a piece as before. Which presses select and which move, and the drag snapping only an anchor, are VectorCraft's own rules. Docs: docs/mcp.md, ROADMAP, docs/target-app-parity.md, docs/ui-parity.md, crates/tools/src/cursors.toml. https://helpx.adobe.com/illustrator/web/add-and-edit-artwork/draw-and-edit-paths/draw-with-quick-pen-tool.html --- ROADMAP.md | 1 + crates/engine/src/tests/quickpen.rs | 137 ++++++++++++++++++++++++ crates/tools/src/cursors.toml | 12 ++- crates/tools/src/quickpen.rs | 98 ++++++++++++++--- crates/tools/src/quickpen/edit.rs | 134 +++++++++++++++++++++++ crates/tools/src/quickpen/tests.rs | 28 +++++ crates/ui-egui/src/menus/context.rs | 10 +- crates/ui-egui/src/tests/contextmenu.rs | 21 ++++ docs/mcp.md | 15 +++ docs/target-app-parity.md | 1 + docs/ui-parity.md | 2 +- 11 files changed, 443 insertions(+), 16 deletions(-) create mode 100644 crates/tools/src/quickpen/edit.rs diff --git a/ROADMAP.md b/ROADMAP.md index 90a6100167..7c7bc4cd7c 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -149,6 +149,7 @@ Ranked; detail in [docs/roadmap.md](docs/roadmap.md) and [docs/gaps.md](docs/gap - 2026-11-17: Circle Tool Options (double-click the Circle tool): Show Center, Show Radii and Show Diameter switch what the tool shows while a circle is drawn, Color sets the color of the center cross and radius lines, Anchors at Standard Positions off puts the circle's anchors at the points it was drawn through (`shape.circleThroughPoints {anchors: "points"}`), and Third Point by Dragging off draws a three-point circle with three clicks and a two-point circle with a double-click on the second point. A VectorCraft addition: headline numbers unchanged. - 2026-11-19: Quick Pen tool, in the Pen tool's group (Alt+P, Option+P on macOS): clicks or drags add straight lines, continuous arcs or sharp-corner arcs; Alt tapped on its own switches the action, C flips the last arc, `[` and `]` size it, a click on the first point closes the path and a click on an open end continues it (`path.quickPen`, part of #2660). Headline numbers unchanged. - 2026-11-19: Quick Pen toolbar on the canvas while the tool is active: Straight Line, Continuous Arc and Sharp Corner Arc, Flip Arc, and More Options with Hide Toolbar, Pin Toolbar Position and Reset Toolbar Position; it follows the drawing beside the path's last point and its handle drags it (`tool.quickPen.flipArc`, `window.quickPenToolbar`, Window › Quick Pen Toolbar; part of #2660). Headline numbers unchanged. +- 2026-11-19: Quick Pen editing: with no path being drawn, a drag on an anchor or a segment of a selected path moves it, a line staying a line and an arc an arc; a click selects an anchor, Shift-click adds one, and the canvas context menu's Delete removes the selected anchors (`path.moveAnchors`, `edit.clear`; #2660). Headline numbers unchanged. - 2026-10-31: Pattern libraries: Window › Swatch Libraries › Patterns and the Swatches panel's library menu open Geometric Patterns, a built-in library of eleven pattern swatches (dots, stripes, checks, a grid and shapes); clicking one adds its pattern and swatch to the document, once, and applies it to the active fill or stroke (`swatch.library.add`). - 2026-11-11: Pattern libraries: Patterns › Grit Textures, a second built-in pattern library, holds eight seamless black textures (Fine Grain, Coarse Grit, Sand, Speckle, Stipple, Scratches, Sparse Flecks and Dense Flecks) on tiles of 18 to 36 pt, each drawn the same way every time; marks that reach past a tile edge continue on the next tile, so the tiles join without a seam (`swatch.library.add`). Scores and estimates unchanged. - 2026-11-11: Pattern libraries: Patterns › Optical Effects, a third built-in pattern library, of VectorCraft's own designs, holds eight black wave, moiré and op-art tiles (Sine Bands, Ripple Lines, Interference Rings, Offset Rings, Warped Checks, Pinched Stripes, Chevron Pulse and Radiating Lenses) of 32 to 48 pt, each drawn the same way every time; each tile is one period of its design, and art that reaches past a tile edge continues on the next tile, so the tiles join without a seam (`swatch.library.add`). Scores and estimates unchanged. diff --git a/crates/engine/src/tests/quickpen.rs b/crates/engine/src/tests/quickpen.rs index f14be809b4..5f41ecedb7 100644 --- a/crates/engine/src/tests/quickpen.rs +++ b/crates/engine/src/tests/quickpen.rs @@ -562,3 +562,140 @@ fn path_quick_pen_replaces_the_points_after_keep() { let ends: Vec = only_path(&s).anchors.iter().map(|a| a.p).collect(); assert_eq!(ends, [pt(0.0, 0.0), pt(100.0, 0.0), pt(200.0, 0.0)]); } + +/// A selected path drawn with `path.quickPen` from `start` through `pieces`, with the Quick Pen +/// chosen and no path being drawn. +fn selected_quick_pen_path(s: &mut Session, start: (f64, f64), pieces: Value) -> NodeId { + let r = s.execute("path.quickPen", &json!({"start": [start.0, start.1], "pieces": pieces})).unwrap(); + let id = NodeId(r["id"].as_u64().unwrap()); + s.execute("select.set", &json!({"ids": [id.0]})).unwrap(); + quick_pen(s); + id +} + +fn points(s: &Session) -> Vec { + only_path(s).anchors.iter().map(|a| a.p).collect() +} + +fn shift_click(s: &mut Session, x: f64, y: f64) { + let v = view(); + let mods = Mods { shift: true, ..Mods::default() }; + for kind in [PointerKind::Down, PointerKind::Up] { + s.pointer(&PointerEvent { mods, ..PointerEvent::new(kind, x, y) }, v).unwrap(); + } +} + +/// Is segment `i` of `sp` a circular arc: do its points a quarter and three quarters along lie on +/// the circle through its ends and its middle? +fn segment_is_circular(sp: &SubPath, i: usize) -> bool { + use vectorcraft_geom::ParamCurve; + let seg = sp.segment(i); + let (a, b, c) = (seg.eval(0.0), seg.eval(0.5), seg.eval(1.0)); + let d = 2.0 * (a.x * (b.y - c.y) + b.x * (c.y - a.y) + c.x * (a.y - b.y)); + let sq = |p: Point| p.x * p.x + p.y * p.y; + let center = pt( + (sq(a) * (b.y - c.y) + sq(b) * (c.y - a.y) + sq(c) * (a.y - b.y)) / d, + (sq(a) * (c.x - b.x) + sq(b) * (a.x - c.x) + sq(c) * (b.x - a.x)) / d, + ); + let r = center.distance(a); + [0.25, 0.75].iter().all(|&t| (seg.eval(t).distance(center) - r).abs() < r * 1e-3) +} + +/// With no path being drawn, a drag on an anchor of the selected path moves that anchor alone, in +/// one undo step: at the corner between a line and an arc, the line stays a line and the arc a +/// circular arc. +#[test] +fn a_drag_on_an_anchor_moves_it_and_the_arc_stays_an_arc() { + let mut s = session(); + selected_quick_pen_path(&mut s, (100.0, 100.0), json!([{"x": 200, "y": 100}, {"x": 300, "y": 100, "action": "sharpArc", "turn": 90}])); + assert_eq!(points(&s), [pt(100.0, 100.0), pt(200.0, 100.0), pt(300.0, 100.0)]); + let undo = undo_steps(&s); + press(&mut s, &[(200.0, 100.0), (200.0, 80.0), (200.0, 50.0)]); + assert_eq!(undo_steps(&s), undo + 1); + let sp = only_path(&s); + assert_eq!(sp.anchors.iter().map(|a| a.p).collect::>(), [pt(100.0, 100.0), pt(200.0, 50.0), pt(300.0, 100.0)]); + assert!(sp.segment_is_line(0), "{:?}", sp.anchors); + assert!(!sp.segment_is_line(1) && segment_is_circular(&sp, 1), "{:?}", sp.anchors); + assert_eq!(paths(&s).len(), 1, "no new path"); +} + +/// A drag on a segment of the selected path moves that segment's two ends. +#[test] +fn a_drag_on_a_segment_moves_its_ends() { + let mut s = session(); + selected_quick_pen_path(&mut s, (100.0, 300.0), json!([{"x": 300, "y": 300}, {"x": 300, "y": 400}])); + press(&mut s, &[(200.0, 300.0), (200.0, 280.0), (200.0, 250.0)]); + assert_eq!(points(&s), [pt(100.0, 250.0), pt(300.0, 250.0), pt(300.0, 400.0)]); + assert_eq!(paths(&s).len(), 1); +} + +/// A drag that starts on an end of the selected open path moves that end; a click there still +/// goes on drawing from it. +#[test] +fn a_drag_on_an_open_end_moves_it() { + let mut s = session(); + let id = selected_quick_pen_path(&mut s, (100.0, 300.0), json!([{"x": 300, "y": 300}])); + press(&mut s, &[(300.0, 300.0), (320.0, 320.0), (350.0, 350.0)]); + assert_eq!(points(&s), [pt(100.0, 300.0), pt(350.0, 350.0)]); + assert!(s.doc().unwrap().selection.partial(id).is_some(), "the dragged end is selected"); + click(&mut s, 350.0, 350.0); + assert!(s.doc().unwrap().selection.partial(id).is_none(), "drawing goes on with the path selected whole"); + click(&mut s, 350.0, 450.0); + assert_eq!(points(&s), [pt(100.0, 300.0), pt(350.0, 350.0), pt(350.0, 450.0)]); +} + +/// A click on an anchor selects it alone, Shift-click adds another, and Delete (`edit.clear`, the +/// context menu's Delete) then removes both. +#[test] +fn clicks_select_anchors_for_delete() { + let mut s = session(); + let id = selected_quick_pen_path(&mut s, (100.0, 100.0), json!([{"x": 200, "y": 100}, {"x": 300, "y": 100}, {"x": 400, "y": 100}])); + let undo = undo_steps(&s); + click(&mut s, 200.0, 100.0); + let picked = |s: &Session| s.doc().unwrap().selection.partial(id).cloned().unwrap_or_default().into_iter().collect::>(); + assert_eq!(picked(&s), [(0, 1)]); + shift_click(&mut s, 300.0, 100.0); + assert_eq!(picked(&s), [(0, 1), (0, 2)]); + shift_click(&mut s, 300.0, 100.0); + assert_eq!(picked(&s), [(0, 1)], "Shift-click takes it out again"); + shift_click(&mut s, 300.0, 100.0); + assert_eq!(undo_steps(&s), undo, "selecting is no edit"); + s.execute("edit.clear", &json!({})).unwrap(); + let left: Vec = paths(&s).iter().flat_map(|(_, pd)| pd.subpaths.iter().flat_map(|sp| sp.anchors.iter().map(|a| a.p))).collect(); + assert!(!left.contains(&pt(200.0, 100.0)) && !left.contains(&pt(300.0, 100.0)), "{left:?}"); +} + +/// Escape during a drag puts the anchor back, and the release then changes nothing. +#[test] +fn escape_takes_back_an_anchor_drag() { + let mut s = session(); + selected_quick_pen_path(&mut s, (100.0, 100.0), json!([{"x": 200, "y": 100}, {"x": 300, "y": 100}])); + let (before, undo) = (points(&s), undo_steps(&s)); + let v = view(); + s.pointer(&PointerEvent::new(PointerKind::Down, 200.0, 100.0), v).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Drag, 200.0, 150.0), v).unwrap(); + assert_ne!(points(&s), before, "the drag previews"); + key(&mut s, ToolKey::Escape); + s.pointer(&PointerEvent::new(PointerKind::Up, 200.0, 150.0), v).unwrap(); + assert_eq!(points(&s), before); + assert_eq!(undo_steps(&s), undo); + assert_eq!(paths(&s).len(), 1); +} + +/// While a path is being drawn, a press on one of its points adds a piece as before; the editing +/// starts only after Escape ends the path. +#[test] +fn a_press_while_drawing_adds_a_piece() { + let mut s = session(); + quick_pen(&mut s); + click(&mut s, 100.0, 100.0); + click(&mut s, 200.0, 100.0); + click(&mut s, 200.0, 200.0); + press(&mut s, &[(200.0, 100.0), (220.0, 90.0), (250.0, 80.0)]); + assert_eq!(points(&s).len(), 4, "a piece added"); + key(&mut s, ToolKey::Escape); + press(&mut s, &[(200.0, 100.0), (200.0, 70.0), (200.0, 50.0)]); + let got = points(&s); + assert_eq!(got.len(), 4); + assert!(got[1].distance(pt(200.0, 50.0)) < 1e-9, "{got:?}"); +} diff --git a/crates/tools/src/cursors.toml b/crates/tools/src/cursors.toml index 0d0106eddb..0b19e3e4c0 100644 --- a/crates/tools/src/cursors.toml +++ b/crates/tools/src/cursors.toml @@ -47,14 +47,20 @@ look = "The same pointer as Arrow, hollow: white with a dark outline." [[cursor]] id = "DirectAnchor" group = "Selection" -shown_when = ["Direct Selection over an anchor of a path that isn't selected."] +shown_when = [ + "Direct Selection over an anchor of a path that isn't selected.", + "The Quick Pen, with no path being drawn, over an anchor of a selected path that is not itself selected (a click selects it, a drag moves it).", +] hotspot = "The arrow's tip." look = "ArrowHollow with a small hollow square badge (an unselected anchor)." [[cursor]] id = "DirectAnchorSelected" group = "Selection" -shown_when = ["Direct Selection over an anchor of a selected path."] +shown_when = [ + "Direct Selection over an anchor of a selected path.", + "The Quick Pen, with no path being drawn, over a selected anchor.", +] hotspot = "The arrow's tip." look = "ArrowHollow with a small filled square badge (a selected anchor)." @@ -137,6 +143,7 @@ shown_when = [ "The Gradient tool over the annotator's handles and during most gradient drags.", "The Perspective Grid and Perspective Selection over plane widgets and handles.", "Selection and Objects on Path over an Objects on Path group's Move All widget, and while dragging it.", + "The Quick Pen, with no path being drawn, over a segment of a selected path, and while a drag moves an anchor or a segment.", ] hotspot = "The centre." look = "A four-way move cursor." @@ -242,6 +249,7 @@ group = "Pen" shown_when = [ "The Pen (not drawing) over an end of an open path (a click continues it).", "The Curvature tool over an open end.", + "The Quick Pen (not drawing) over an end of an open path (a click continues it, a drag on a selected path's end moves it).", ] hotspot = "The nib's tip." look = "The Pen nib with a slash badge." diff --git a/crates/tools/src/quickpen.rs b/crates/tools/src/quickpen.rs index 6368ba160b..290c0f494a 100644 --- a/crates/tools/src/quickpen.rs +++ b/crates/tools/src/quickpen.rs @@ -12,6 +12,9 @@ //! point closes the path, a click on an end of an open path goes on drawing from it, and Escape //! or Enter ends the path. The path's points show as circles, without handles, and a preview //! shows the piece the next click adds. Points snap to Smart Guides. Each piece is one undo step. +//! While no path is being drawn, the tool edits the selected paths ([`edit`]). + +mod edit; use std::f64::consts::{FRAC_PI_2, PI}; use std::sync::Arc; @@ -24,6 +27,7 @@ use crate::draw2::FEEDBACK; use crate::guides::{DrawSnap, Leave}; use crate::pen::{continue_from, open_end_at}; use crate::{Action, Cursor, Mods, Overlay, PointerEvent, PointerKind, Tool, ToolContext, ToolKey}; +use edit::{Edit, Grab}; /// The tool's id. pub const ID: &str = "quickPen"; @@ -282,13 +286,15 @@ pub struct QuickPenTool { turn: f64, drawing: Option, press: Option, + /// A press on an anchor or a segment of a selected path while no path is being drawn. + edit: Option, hover: Option, snap: DrawSnap, } impl Default for QuickPenTool { fn default() -> Self { - Self { action: Stroke::Line, turn: DEFAULT_TURN, drawing: None, press: None, hover: None, snap: DrawSnap::default() } + Self { action: Stroke::Line, turn: DEFAULT_TURN, drawing: None, press: None, edit: None, hover: None, snap: DrawSnap::default() } } } @@ -409,8 +415,9 @@ impl QuickPenTool { } /// What a press draws: a piece on the path being drawn, its closing piece, or a new path (from - /// an end of an open path, the path goes on). - fn press_down(&mut self, cx: &ToolContext, p: Point) -> Vec { + /// an end of an open path, the path goes on). With no path being drawn, a press on an anchor + /// or a segment of a selected path waits to see whether it drags ([`edit`]). + fn press_down(&mut self, cx: &ToolContext, p: Point, shift: bool) -> Vec { if self.drawing.is_some() && self.active(cx).is_none() { self.drawing = None; } @@ -442,30 +449,75 @@ impl QuickPenTool { self.press = Some(Press { at: p, dragged: false, begun: true }); return vec![Action::Begin("Quick Pen".into()), Action::Preview(COMMAND.into(), self.params(false)), drawn()]; } + if let Some(grab) = edit::grab_at(cx, p, tol) { + self.edit = Some(Edit::new(grab, p, shift)); + return vec![]; + } if let Some((id, si, at_first)) = open_end_at(cx, p, tol, None) && cx.doc.is_editable(id) { - // From its start, `continue_from` reverses the path first; the tool then sees it. - self.drawing = Some(Drawing { id: Some(id), si, ..Drawing::default() }); - let mut out = continue_from(cx, id, si, at_first); - out.push(drawn()); - return out; + return self.continue_path(cx, id, si, at_first); } + self.start_path(cx, p) + } + + /// Goes on drawing from an end of subpath `si` of path `id`. + fn continue_path(&mut self, cx: &ToolContext, id: NodeId, si: usize, at_first: bool) -> Vec { + // From its start, `continue_from` reverses the path first; the tool then sees it. + self.drawing = Some(Drawing { id: Some(id), si, ..Drawing::default() }); + let mut out = vec![]; + // Anchors selected by an earlier click or drag: the path is selected whole again. + if !cx.selection.anchors.is_empty() || !cx.selection.segments.is_empty() { + let top = cx.doc.parent_of(id).filter(|p| cx.doc.node(*p).is_some_and(|n| matches!(n.kind, NodeKind::Compound { .. }))).unwrap_or(id); + out.push(Action::Exec("select.set".into(), json!({"ids": [top.0]}))); + } + out.extend(continue_from(cx, id, si, at_first)); + out.push(drawn()); + out + } + + /// Starts a new path at `p`. + fn start_path(&mut self, cx: &ToolContext, p: Point) -> Vec { let q = self.snap.press(cx, p, &[], None); self.drawing = Some(Drawing { start: Some(q), ..Drawing::default() }); vec![Action::Exec(COMMAND.into(), self.params(false)), Action::Notify("created".into())] } - /// Ends the path being drawn; a press that added a piece is taken back. + /// Ends the path being drawn; a press that added a piece, or moved part of a path, is taken + /// back. fn end(&mut self) -> Vec { self.drawing = None; self.snap.clear(); + let moved = self.edit.take().is_some_and(|e| e.began); match self.press.take() { Some(pr) if pr.begun => vec![Action::Cancel], + _ if moved => vec![Action::Cancel], _ => vec![], } } + /// The release of a press on an anchor or a segment of a selected path: a drag moves what it + /// holds to `p` and ends its undo step. A click on an end of an open path goes on drawing from + /// it, a click on another anchor selects it alone (with Shift, adds it to the selected anchors + /// or takes it out), and a click on a segment starts a new path there. + fn release_edit(&mut self, cx: &ToolContext, mut e: Edit, p: Point) -> Vec { + if e.began { + let mut out = e.drag(cx, p); + out.push(Action::Commit); + return out; + } + match e.grab { + Grab::Anchor { id, si, ai, .. } if e.shift => { + vec![Action::Exec("select.anchors".into(), json!({"id": id.0, "anchors": [[si, ai]], "mode": "toggle"}))] + } + Grab::Anchor { id, si, ai, end: true, .. } => self.continue_path(cx, id, si, ai == 0), + Grab::Anchor { id, si, ai, .. } => { + vec![Action::Exec("select.anchors".into(), json!({"id": id.0, "anchors": [[si, ai]], "mode": "set"}))] + } + Grab::Segment { .. } => self.start_path(cx, e.start), + } + } + /// The piece the next click adds, from the end of `sp` to `h`, as a path to preview. fn rubber_band(&self, sp: &SubPath, h: Point) -> Option { let n = sp.anchors.len(); @@ -490,7 +542,7 @@ impl Tool for QuickPenTool { } fn busy(&self) -> bool { - self.press.is_some() + self.press.is_some() || self.edit.is_some() } fn pointer(&mut self, cx: &ToolContext, ev: &PointerEvent) -> Vec { @@ -502,12 +554,18 @@ impl Tool for QuickPenTool { vec![] } PointerKind::Down => { - if self.press.is_some() { + if self.press.is_some() || self.edit.is_some() { return vec![]; } - self.press_down(cx, p) + self.press_down(cx, p, ev.mods.shift) } PointerKind::Drag => { + if let Some(e) = self.edit.as_mut() { + if !e.began && p.distance(e.start) < cx.tol(DRAG_PX) { + return vec![]; + } + return e.drag(cx, p); + } let Some(mut pr) = self.press else { return vec![] }; if !pr.dragged && p.distance(pr.at) < cx.tol(DRAG_PX) { return vec![]; @@ -520,6 +578,9 @@ impl Tool for QuickPenTool { self.drag_to(cx, p) } PointerKind::Up => { + if let Some(e) = self.edit.take() { + return self.release_edit(cx, e, p); + } let out = match self.press { // The piece ends where the press is let go, also past the last drag. Some(pr) if pr.begun => { @@ -595,6 +656,8 @@ impl Tool for QuickPenTool { /// The drawing goes on only when the path is back as it was before the press. fn drop_press(&mut self, cx: &ToolContext) -> Vec { self.snap.clear(); + // The session takes back what an edit moved; the release that follows does nothing. + self.edit = None; if self.press.take().is_some_and(|pr| pr.begun) && let Some(dr) = self.drawing.as_mut() { @@ -655,8 +718,10 @@ impl Tool for QuickPenTool { fn deactivate(&mut self, _cx: &ToolContext) -> Vec { self.drawing = None; self.snap.clear(); + let moved = self.edit.take().is_some_and(|e| e.began); match self.press.take() { Some(pr) if pr.begun => vec![Action::Commit], + _ if moved => vec![Action::Commit], _ => vec![], } } @@ -674,6 +739,9 @@ impl Tool for QuickPenTool { fn overlays(&self, cx: &ToolContext) -> Vec { let mut o = self.snap.guides().to_vec(); + if let Some(e) = &self.edit { + o.extend(e.guides.iter().cloned()); + } let Some((id, sp)) = self.active(cx) else { return o }; if self.press.is_none() && let Some(h) = self.hover @@ -703,6 +771,12 @@ impl Tool for QuickPenTool { let close = sp.anchors.len() >= 2 && sp.anchors.first().is_some_and(|f| f.p.distance(p) <= tol); return if close { Cursor::PenClose } else { Cursor::PenDrawing }; } + if let Some(e) = &self.edit { + return if e.began { Cursor::Move } else { edit::cursor(cx, e.grab) }; + } + if let Some(grab) = edit::grab_at(cx, p, tol) { + return edit::cursor(cx, grab); + } if open_end_at(cx, p, tol, None).is_some() { Cursor::PenContinue } else { Cursor::Pen } } diff --git a/crates/tools/src/quickpen/edit.rs b/crates/tools/src/quickpen/edit.rs new file mode 100644 index 0000000000..ee219a8d63 --- /dev/null +++ b/crates/tools/src/quickpen/edit.rs @@ -0,0 +1,134 @@ +//! Editing with the Quick Pen while no path is being drawn: a drag on an anchor of a selected path +//! moves it, and a drag on one of its segments moves that segment (`path.moveAnchors` with +//! `interpolate`: a segment with one moved end is turned and scaled to its new ends, so a line +//! stays a line and an arc stays an arc of the same angle; at a smooth point, where two arcs join, +//! the handles stay in line and the arcs bend to meet). The moved anchor snaps as a Direct +//! Selection drag's does. A click on an anchor selects it, Shift-click adds it to the selected anchors or takes it +//! out, and the canvas context menu's Delete then removes them (`edit.clear`). A click on an end +//! of an open path goes on drawing from it, as before. + +use std::collections::BTreeSet; + +use serde_json::json; +use vectorcraft_doc::{AnchorRef, NodeId, Selection}; +use vectorcraft_geom::Point; + +use crate::draw2::{anchor_in, segment_in, shown_paths}; +use crate::guides::{PointSnap, Targets}; +use crate::{Action, Cursor, Overlay, ToolContext}; + +/// What a press holds. +#[derive(Clone, Copy, Debug, PartialEq)] +pub(super) enum Grab { + /// Anchor `ai` of subpath `si` of path `id`, at `at`; `end` when it is an end of an open subpath. + Anchor { id: NodeId, si: usize, ai: usize, at: Point, end: bool }, + /// The segment from anchor `seg` of subpath `si` of path `id` to the next one. + Segment { id: NodeId, si: usize, seg: usize }, +} + +impl Grab { + /// The path the grab is on. + pub(super) fn id(self) -> NodeId { + match self { + Grab::Anchor { id, .. } | Grab::Segment { id, .. } => id, + } + } + + /// The anchors the drag moves when they are not already selected: the anchor, or the + /// segment's two ends. + fn anchors(self, cx: &ToolContext) -> Option> { + match self { + Grab::Anchor { si, ai, .. } => Some(vec![(si, ai)]), + Grab::Segment { id, si, seg } => { + let n = cx.doc.node(id)?.path_data()?.subpaths.get(si)?.anchors.len(); + Some(vec![(si, seg), (si, (seg + 1).checked_rem(n)?)]) + } + } + } +} + +/// An anchor or a segment of a selected path under `p`, within the tool's point tolerance `tol`. +/// Anchors come before segments. +pub(super) fn grab_at(cx: &ToolContext, p: Point, tol: f64) -> Option { + let shown = shown_paths(cx); + if let Some((id, si, ai)) = anchor_in(cx, shown.iter().copied(), p, tol) { + let sp = cx.doc.node(id)?.path_data()?.subpaths.get(si)?; + let at = sp.anchors.get(ai)?.p; + let end = !sp.closed && (ai == 0 || ai + 1 == sp.anchors.len()); + return Some(Grab::Anchor { id, si, ai, at, end }); + } + segment_in(cx, shown, p, tol).map(|(id, si, seg, _)| Grab::Segment { id, si, seg }) +} + +/// The cursor over `grab`: an open end shows that a click goes on drawing from it, another anchor +/// that it can be selected and moved, and a segment that it moves. +pub(super) fn cursor(cx: &ToolContext, grab: Grab) -> Cursor { + match grab { + Grab::Anchor { end: true, .. } => Cursor::PenContinue, + Grab::Anchor { id, si, ai, .. } if cx.selection.partial(id).is_some_and(|s| s.contains(&(si, ai))) => Cursor::DirectAnchorSelected, + Grab::Anchor { .. } => Cursor::DirectAnchor, + Grab::Segment { .. } => Cursor::Move, + } +} + +/// A press on an anchor or a segment of a selected path, while no path is being drawn. +pub(super) struct Edit { + pub(super) grab: Grab, + /// Where the press went down. + pub(super) start: Point, + pub(super) shift: bool, + /// Whether the press has dragged far enough to move what it holds (an undo step began). + pub(super) began: bool, + snap: Option, + pub(super) guides: Vec, +} + +impl Edit { + pub(super) fn new(grab: Grab, start: Point, shift: bool) -> Self { + Self { grab, start, shift, began: false, snap: None, guides: vec![] } + } + + /// Moves what the press holds by the drag to `p`. The first move selects the anchor, or the + /// segment, unless it is already selected, and begins the undo step; a drag that starts on + /// one of several selected anchors moves them all. + pub(super) fn drag(&mut self, cx: &ToolContext, p: Point) -> Vec { + let mut out = vec![]; + if !self.began { + let id = self.grab.id(); + let Some(picked) = self.grab.anchors(cx) else { return out }; + let already = cx.selection.partial(id).is_some_and(|s| picked.iter().all(|a| s.contains(a))); + let moving = if already { + cx.selection.clone() + } else { + out.push(match self.grab { + Grab::Anchor { si, ai, .. } => Action::Exec("select.anchors".into(), json!({"id": id.0, "anchors": [[si, ai]], "mode": "set"})), + Grab::Segment { si, seg, .. } => { + Action::Exec("select.segments".into(), json!({"id": id.0, "segments": [[si, seg]], "mode": "set"})) + } + }); + let mut sel = Selection { objects: vec![id], ..Selection::default() }; + sel.anchors.insert(id, picked.into_iter().collect::>()); + sel + }; + out.push(Action::Begin("Move".into())); + // A held anchor snaps; the anchors and segments that stay put are targets too. + if matches!(self.grab, Grab::Anchor { .. }) { + self.snap = Some(PointSnap::moving(cx, || Targets::for_anchor_drag(cx.doc, &moving))); + } + self.began = true; + } + let d = match (self.grab, &self.snap) { + (Grab::Anchor { at, .. }, Some(snap)) => { + let (q, guides) = snap.snap_from(cx, at + (p - self.start), None); + self.guides = guides; + q - at + } + _ => p - self.start, + }; + if !d.x.is_finite() || !d.y.is_finite() { + return out; + } + out.push(Action::Preview("path.moveAnchors".into(), json!({"dx": d.x, "dy": d.y, "interpolate": true}))); + out + } +} diff --git a/crates/tools/src/quickpen/tests.rs b/crates/tools/src/quickpen/tests.rs index f5ab9986d1..0d316c8428 100644 --- a/crates/tools/src/quickpen/tests.rs +++ b/crates/tools/src/quickpen/tests.rs @@ -196,6 +196,34 @@ fn the_first_click_starts_a_path() { assert_eq!(t.cursor(&cx, pt(400.0, 400.0), Mods::default()), Cursor::Pen); } +/// With no path being drawn, the cursor over a selected path shows what a press there does: an +/// anchor is selected and moved, a selected anchor shows as one, and a segment moves. A press there +/// waits for a drag or a release instead of starting a path. +#[test] +fn a_selected_paths_anchors_and_segments_show_the_edit_cursors() { + let (d, id) = doc_with_rect(); + let mut s = Selection::default(); + s.set([id]); + let p = paint(); + let cx = cx(&d, &s, &p); + let mut t = QuickPenTool::default(); + assert_eq!(t.cursor(&cx, pt(100.0, 100.0), Mods::default()), Cursor::DirectAnchor); + assert_eq!(t.cursor(&cx, pt(150.0, 100.0), Mods::default()), Cursor::Move); + assert_eq!(t.cursor(&cx, pt(400.0, 400.0), Mods::default()), Cursor::Pen); + assert!(t.pointer(&cx, &PointerEvent::new(PointerKind::Down, 150.0, 100.0)).is_empty()); + assert!(t.busy()); + let a = t.pointer(&cx, &PointerEvent::new(PointerKind::Drag, 150.0, 130.0)); + assert!(matches!(&a[0], Action::Exec(c, v) if c == "select.segments" && v["mode"] == "set"), "{a:?}"); + assert!(matches!(&a[2], Action::Preview(c, v) if c == "path.moveAnchors" && v["dy"] == 30.0 && v["interpolate"] == true), "{a:?}"); + assert_eq!(t.cursor(&cx, pt(150.0, 130.0), Mods::default()), Cursor::Move); + let up = t.pointer(&cx, &PointerEvent::new(PointerKind::Up, 150.0, 130.0)); + assert_eq!(up.last(), Some(&Action::Commit)); + assert!(!t.busy()); + s.anchors.insert(id, (0..4).map(|ai| (0, ai)).collect()); + let cx = crate::testutil::cx(&d, &s, &p); + assert_eq!(t.cursor(&cx, pt(100.0, 100.0), Mods::default()), Cursor::DirectAnchorSelected); +} + /// The rubber band previews exactly the piece a click adds. #[test] fn the_rubber_band_is_the_next_piece() { diff --git a/crates/ui-egui/src/menus/context.rs b/crates/ui-egui/src/menus/context.rs index d80b69038b..004ee0e37a 100644 --- a/crates/ui-egui/src/menus/context.rs +++ b/crates/ui-egui/src/menus/context.rs @@ -54,7 +54,15 @@ pub fn context_items(app: &VectorcraftApp) -> Vec { c("Select All", "select.all"), ]); } else { - v.extend([c("Cut", "edit.cut"), c("Copy", "edit.copy"), c("Paste", "edit.paste"), Sep]); + v.extend([c("Cut", "edit.cut"), c("Copy", "edit.copy"), c("Paste", "edit.paste")]); + // With the Quick Pen, Delete removes the selected anchor points, or the selected objects + // (`edit.clear`), as the public + // [Draw with the Quick Pen tool](https://helpx.adobe.com/illustrator/web/add-and-edit-artwork/draw-and-edit-paths/draw-with-quick-pen-tool.html) + // page describes for removing a path. + if app.session.tool_id() == vectorcraft_tools::quickpen::ID { + v.push(c("Delete", "edit.clear")); + } + v.push(Sep); // With one group or compound path selected the menu has Isolate Selected Group, and with // one path selected (a member of a group or a compound path too) it has Isolate Selected // Path, as the help page diff --git a/crates/ui-egui/src/tests/contextmenu.rs b/crates/ui-egui/src/tests/contextmenu.rs index 781924d1a1..afe854c6a8 100644 --- a/crates/ui-egui/src/tests/contextmenu.rs +++ b/crates/ui-egui/src/tests/contextmenu.rs @@ -214,6 +214,27 @@ fn labels(items: &[Item]) -> Vec<&'static str> { .collect() } +/// With the Quick Pen, the menu has Delete, which removes the selected anchor points; with another +/// tool it does not. +#[test] +fn the_quick_pen_menu_deletes_the_selected_anchors() { + let mut app = app(); + let a = rect(&mut app, 0.0, 0.0); + app.run("select.anchors", json!({"id": a.0, "anchors": [[0, 0]], "mode": "set"})).unwrap(); + assert!(!labels(&menus::context_items(&app)).contains(&"Delete"), "the Selection tool"); + app.select_tool("quickPen"); + let items = menus::context_items(&app); + assert!(labels(&items).contains(&"Delete"), "{:?}", labels(&items)); + assert!(items.iter().any(|it| matches!(it, Item::Cmd("Delete", "edit.clear", _)))); + menus::invoke(&mut app, "edit.clear", json!({})); + let st = app.session.active().unwrap(); + let pd = st.doc.node(a).unwrap().path_data().unwrap().clone(); + assert_eq!(pd.subpaths[0].anchors.len(), 3, "one anchor removed"); + // Nothing selected: no Delete. + app.run("select.none", json!({})).unwrap(); + assert!(!labels(&menus::context_items(&app)).contains(&"Delete")); +} + #[test] fn the_menu_follows_the_selection() { let mut app = app(); diff --git a/docs/mcp.md b/docs/mcp.md index e7abf476a9..add7833de6 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -7339,6 +7339,21 @@ toolbar its controls wrap onto more rows. `ui.inspect` gives `quickPenToolbar` ( the pin and whether it shows are not saved. These commands run in the desktop app; the headless host does not run them, so they need `--connect`. +With no path being drawn (after Escape or Enter, or before the first click), the tool edits the selected paths, as +[Draw with the Quick Pen tool](https://helpx.adobe.com/illustrator/web/add-and-edit-artwork/draw-and-edit-paths/draw-with-quick-pen-tool.html) +describes. A drag on one of their anchors moves that anchor, and a drag that starts on one of several selected anchors +moves them all; a drag on a segment moves that segment's two ends. The tool selects what it moves +(`select.anchors` or `select.segments` with `mode: "set"`) and moves it with `path.moveAnchors {dx, dy, interpolate: +true}`, one undo step per drag: a segment with one moved end is turned and scaled to its new ends, so a line stays a +line and an arc stays an arc through the same angle, and at a smooth point the handles stay in line. A dragged anchor +snaps to Smart Guides; a dragged segment does not. Escape during the drag takes it back. A click on an anchor selects +it alone and Shift-click adds it to the selected anchors or takes it out (`select.anchors` with `"set"` or +`"toggle"`). A click on an end of an open path still goes on drawing from it, a drag there moves the end, and a click +on a segment starts a new path. With the Quick Pen chosen, the canvas context menu (right-click) has Delete, which +removes the selected anchors, or the selected objects (`edit.clear {}`). While a path is being drawn, a press on it +adds a piece as before. Which presses select, which move, and the drag snapping only an anchor are VectorCraft's own +rules. + `path.quickPen {start?: [x, y], id?, subpath?, keep?, pieces?, closed?}` draws such a path and selects it, as one undo step, and answers `{id}`. With `start`, it makes a new path with the current paint (a black stroke when the paint has neither fill nor stroke). With `id`, it draws on the open subpath `subpath` (0 when left out) of that path: its diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index b1d981428a..5058e1f6df 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -634,6 +634,7 @@ since 2026-10-01. - **Trim View hides guides and the grid (#8363):** while View › Trim View is on, the canvas and tiled panes draw no ruler guides, no guide paths and no grid, the guides are neither snapped to nor picked, and Show/Hide Guides and Show/Hide Grid are greyed out (menu bar, canvas context menu, Properties) and refuse to run; the stored choices come back when it is turned off, and the rulers stay ([trim view hides guides](https://community.adobe.com/t5/illustrator-discussions/trim-view-hides-guides/td-p/14066140), [guides greyed out](https://community.adobe.com/t5/illustrator-discussions/guides-greyed-out/m-p/11132728)). A drag or double-click on a ruler makes no guide while it is on (no preview, no undo step, a status message). `trim_view_hides_the_guides_and_the_grid`, `trim_view_deselects_selected_guide_paths`, `trim_view_makes_no_guide_from_the_rulers` in `crates/ui-egui/src/canvas/tests.rs`; `trim_view_greys_out_show_guides_and_show_grid` in `crates/ui-egui/src/menus/tests.rs`. - **Recolor picker follow-up (#8031/#4028):** native Lab numeric entry, document/loaded-library swatches in the Color Picker, and Assign-row Pick from Swatches / Limit to Library menus. #4090 provided the double-click picker and #5113 the Assign sliders. Regression tests `native_lab_entry_in_color_picker` and `row_context_menu_pick_from_swatches_and_limit_to_library` exercise the fields and menu callbacks rather than writing their result state. Area score and hours unchanged. +- **Quick Pen editing (#2660):** with no path being drawn, the Quick Pen tool moves an anchor or a segment of a selected path by a drag (`path.moveAnchors` with `interpolate`, one undo step, a line staying a line and an arc an arc), selects an anchor with a click and adds one with Shift-click, and the canvas context menu's Delete removes the selected anchors (`edit.clear`), as [Draw with the Quick Pen tool](https://helpx.adobe.com/illustrator/web/add-and-edit-artwork/draw-and-edit-paths/draw-with-quick-pen-tool.html) describes. Which presses select and which move, and the drag snapping only an anchor, are VectorCraft's own rules. Tests: tools `quickpen::tests::a_selected_paths_anchors_and_segments_show_the_edit_cursors`, engine `tests::quickpen` (`a_drag_on_an_anchor_moves_it_and_the_arc_stays_an_arc`, `a_drag_on_a_segment_moves_its_ends`, `a_drag_on_an_open_end_moves_it`, `clicks_select_anchors_for_delete`, `escape_takes_back_an_anchor_drag`, `a_press_while_drawing_adds_a_piece`), ui-egui `tests::contextmenu::the_quick_pen_menu_deletes_the_selected_anchors`. Score and hours unchanged. - **Quick Pen tool (#2660, in part):** a tool in the Pen tool's group (Alt+P, Option+P on macOS) draws straight lines, continuous arcs and sharp-corner arcs, one undo step per piece; Alt pressed and let go on its own switches the action, C flips the last sharp-corner arc, `[` and `]` change the arc size by 15°, a click on the first point closes the path, a click on an open end continues it, and Escape or Enter ends it (`path.quickPen`), as [Draw with the Quick Pen tool](https://helpx.adobe.com/illustrator/web/add-and-edit-artwork/draw-and-edit-paths/draw-with-quick-pen-tool.html) and [Quick Pen tool keyboard shortcuts](https://helpx.adobe.com/illustrator/web/add-and-edit-artwork/draw-and-edit-paths/quick-pen-tool-keyboard-shortcuts.html) describe. The 180° default arc, its 15° steps, the side an arc bulges to, a dragged piece ending where the press is let go, and C, `[` and `]` changing the arc being dragged are VectorCraft's own rules. Tests: tools `quickpen::tests`, engine `tests::quickpen`, ui-egui `shortcuts::alt_tap::tests`, `alt_p_chooses_the_quick_pen_and_an_alt_tap_switches_its_action` and `brackets_size_the_quick_pen_arc_being_dragged`. Score and hours unchanged. - **Optional compact Tools (#7234):** Window > Toolbars > Compact Tools reduces row and column spacing and the main panel's allocated width in one or two columns, docked or floating. The setting is saved with the UI state and applies to Basic, Advanced and edited main Tools layouts; the selected tool, icon size, footer controls and tool-flyout behavior are retained. Turning it off restores the existing layout, which remains the default. Named custom toolbars and flyout spacing are unchanged. Public regressions in `crates/ui-egui/tests/toolbar_compact.rs` cover the actual toolbar layout against the default control, the command and saved-state roundtrip, tool selection, flyouts, footer controls and short-window reachability. This is an optional layout choice, without a styling-parity or score claim; hours are unchanged. diff --git a/docs/ui-parity.md b/docs/ui-parity.md index 911f08d192..7122033e47 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -205,7 +205,7 @@ tools, never checked side by side) isn't captured row by row. | Busy cursor during long operations | done | Background open, save and export show the system progress cursor (gap G1) | | Each anchor snaps to Smart Guides and construction angles | done | `DrawSnap` | | Curvature tool: click/drag points, double-click or Alt-click for a corner, temporary Direct Selection, point conversion | partial | circular point markers without direction handles or duplicate markers, Anchor Size and Hide Edges regression-tested (#1236, in part); curve geometry: each stretch of three points follows the circle through them (handles along its tangent, chord/(3·cos²(α/2)) long, shorter in a turn tighter than 30°), open ends curving in, the same rule for the rubber band, dragged, inserted and converted points (#1236, in part); neighbours of a point dragged on an existing path keep their tangents, and modifiers requested in #975 remain | -| Quick Pen tool: straight lines, continuous arcs and sharp-corner arcs, Alt/Option to switch action, C to flip an arc, `[` / `]` for its size, Alt+P / Option+P, close on the first point, continue from an end, Escape to end ([help page](https://helpx.adobe.com/illustrator/web/add-and-edit-artwork/draw-and-edit-paths/draw-with-quick-pen-tool.html), [shortcuts](https://helpx.adobe.com/illustrator/web/add-and-edit-artwork/draw-and-edit-paths/quick-pen-tool-keyboard-shortcuts.html)) | partial | `path.quickPen` and the tool in `crates/tools/src/quickpen.rs`, in the Pen tool's group (#2660); the on-canvas toolbar with its actions, Flip Arc and its More menu (Hide Toolbar and Reset Toolbar Position, and VectorCraft's own Pin Toolbar Position) in `crates/ui-egui/src/canvas/quick_pen_bar.rs`. Not yet: dragging a path's ends to change a line's or arc's length, Ctrl+scroll for the arc size, and editing and deleting with the tool | +| Quick Pen tool: straight lines, continuous arcs and sharp-corner arcs, Alt/Option to switch action, C to flip an arc, `[` / `]` for its size, Alt+P / Option+P, close on the first point, continue from an end, Escape to end, drag anchors or segments to edit, right-click Delete ([help page](https://helpx.adobe.com/illustrator/web/add-and-edit-artwork/draw-and-edit-paths/draw-with-quick-pen-tool.html), [shortcuts](https://helpx.adobe.com/illustrator/web/add-and-edit-artwork/draw-and-edit-paths/quick-pen-tool-keyboard-shortcuts.html)) | partial | `path.quickPen` and the tool in `crates/tools/src/quickpen.rs`, in the Pen tool's group (#2660); the on-canvas toolbar with its actions, Flip Arc and its More menu (Hide Toolbar and Reset Toolbar Position, and VectorCraft's own Pin Toolbar Position) in `crates/ui-egui/src/canvas/quick_pen_bar.rs`; with no path being drawn, drags on a selected path's anchors and segments move them (`quickpen/edit.rs`, `path.moveAnchors`), clicks select anchors, and the canvas context menu has Delete (`edit.clear`). Not yet: dragging a path's ends to change a line's or arc's length, and Ctrl+scroll for the arc size | | Icon-strip flyout resizing (#5713) | done | Canvas-side edge and bottom; user size persists after reopening and workspace restore; Glyphs and Artboards pointer/cursor regression | | Icon-strip flyout resizing from the top (storytold/craft-libs#1094) | done | Top edge (a 4 pt band over the tab strip) and the canvas-side top corner; the bottom and the icon-column edge stay; the moved top persists after reopening and workspace restore; `an_icon_flyout_grows_upward_from_its_top_edge_and_free_corner` | | Graphic Styles list fills a taller panel (#2992) | done | Docked, floating or in a resized flyout, the list takes the height above the panel's footer, as the Artboards list does; outside a sized panel it stays 220 pt; `the_list_fills_a_tall_panel_above_its_footer` | From 10373c02a655b0d8738dbcadeeb3b535e29c33ba Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 19 Nov 2026 17:27:17 -0800 Subject: [PATCH 009/151] Color Wheel: the ui.colorWheel description names the document's RGB space for oklch The command rejects sliders: oklch while the active document's RGB space (its assigned profile, else the working RGB space) is not sRGB. Both catalog descriptions now say so. --- crates/mcp/src/ui_catalog.rs | 2 +- crates/ui-egui/src/menus/ui_commands.rs | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/crates/mcp/src/ui_catalog.rs b/crates/mcp/src/ui_catalog.rs index 2d0c977391..1d0a0227cf 100644 --- a/crates/mcp/src/ui_catalog.rs +++ b/crates/mcp/src/ui_catalog.rs @@ -1604,7 +1604,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "ui.colorWheel", "Color Wheel Options", "", - "{view?: wheel|box, channel?: hue|saturation|brightness|red|green|blue, sliders?: none|oklch|hsl, gamut?: bool, harmony?: bool, harmonyRule?: complementary|splitComplementary|leftComplement|rightComplement|analogous|analogous2|triad|tetrad|tetrad2|tetrad3|compound|compound2|highContrast|highContrast3|pentagram, vision?: bool, documentColors?: bool} show the Color Wheel panel's wheel or its box, as the panel menu's Wheel View and Box View do, pick the box's channel, as Box Channel does, and show no slider rows under the wheel or the box (none), OKLCH Sliders (oklch) or HSL Sliders (hsl), as the menu items of those names do: the box is a color field with the channel's strip at its right, and the field shows the other two components (hue: saturation across and brightness up; saturation: hue across and brightness up; brightness: hue across and saturation up; red: blue across and green up; green: blue across and red up; blue: red across and green up); OKLCH Sliders edit lightness 0 to 100 %, chroma 0 to 100 % of 0.4 and hue 0 to 360°, CSS Color 4's OKLCH of the display sRGB, and a color outside sRGB keeps L and H and takes the largest chroma that fits at or below the one asked for; HSL Sliders edit hue 0 to 360°, saturation 0 to 100 % and lightness 0 to 100 %, CSS Color 4's HSL of the display sRGB; gamut true grays out the parts of the wheel's square and the box's field whose colors the CMYK space cannot print (the out-of-gamut warning's test, as color.gamutCheck answers it), as Show Out-of-Gamut Colors does, and false shows them again; the shading is approximate: each cell of a 16 by 16 grid over the square or the field is grayed out or not by the color at its center, so a grayed cell can hold printable colors and a clear cell can hold colors that cannot print; harmony shows a marker on the wheel's ring for each other color of harmonyRule (the Color Guide's rule of that id; a rule's label is taken too), as Show Harmony and Harmony Rule do, and a click on a marker applies its color; vision shows Show Color Vision Preview's row under the wheel or the box, four chips with the current color as simulated for protanopia, deuteranopia and tritanopia (the simulations of view.proofSetup's protanopia, deuteranopia and tritanopia targets) and for achromatopsia (the gray with the color's CIE L*), each named with its hex value in its tooltip and to screen readers, and taking the keyboard focus; a click or a key on a chip does not apply its color; documentColors shows or hides the row the panel menu's Show Document Colors adds under the wheel or the box: the colors color.used {} lists, headed Selection Colors when something is selected and Document Colors otherwise, most used first and as many as fit in one row (a chip's tooltip gives its hex value and how many times the art uses it; a click applies it to the active proxy or to the selected gradient stop, keeping its color model and its link to a global swatch, or to the selected freeform point, which takes the color alone, and Alt+click applies it to the other proxy; the row reads the colors again when the document or the selection changes, not during a drag, and in art with more than 5,000 color uses at most once every half second after an edit); keys left out or null keep their values ({} reads them), params that are not an object, another key or a value off the list are an error and change nothing, oklch is an error while the working RGB space is not sRGB, the settings are kept with the preferences, and the command does not open the panel (window.panel {panel: \"colorWheel\"} does) (ui.inspect: ui.color_wheel) → {view, channel, sliders, gamut, harmony, harmonyRule, vision, documentColors}", + "{view?: wheel|box, channel?: hue|saturation|brightness|red|green|blue, sliders?: none|oklch|hsl, gamut?: bool, harmony?: bool, harmonyRule?: complementary|splitComplementary|leftComplement|rightComplement|analogous|analogous2|triad|tetrad|tetrad2|tetrad3|compound|compound2|highContrast|highContrast3|pentagram, vision?: bool, documentColors?: bool} show the Color Wheel panel's wheel or its box, as the panel menu's Wheel View and Box View do, pick the box's channel, as Box Channel does, and show no slider rows under the wheel or the box (none), OKLCH Sliders (oklch) or HSL Sliders (hsl), as the menu items of those names do: the box is a color field with the channel's strip at its right, and the field shows the other two components (hue: saturation across and brightness up; saturation: hue across and brightness up; brightness: hue across and saturation up; red: blue across and green up; green: blue across and red up; blue: red across and green up); OKLCH Sliders edit lightness 0 to 100 %, chroma 0 to 100 % of 0.4 and hue 0 to 360°, CSS Color 4's OKLCH of the display sRGB, and a color outside sRGB keeps L and H and takes the largest chroma that fits at or below the one asked for; HSL Sliders edit hue 0 to 360°, saturation 0 to 100 % and lightness 0 to 100 %, CSS Color 4's HSL of the display sRGB; gamut true grays out the parts of the wheel's square and the box's field whose colors the CMYK space cannot print (the out-of-gamut warning's test, as color.gamutCheck answers it), as Show Out-of-Gamut Colors does, and false shows them again; the shading is approximate: each cell of a 16 by 16 grid over the square or the field is grayed out or not by the color at its center, so a grayed cell can hold printable colors and a clear cell can hold colors that cannot print; harmony shows a marker on the wheel's ring for each other color of harmonyRule (the Color Guide's rule of that id; a rule's label is taken too), as Show Harmony and Harmony Rule do, and a click on a marker applies its color; vision shows Show Color Vision Preview's row under the wheel or the box, four chips with the current color as simulated for protanopia, deuteranopia and tritanopia (the simulations of view.proofSetup's protanopia, deuteranopia and tritanopia targets) and for achromatopsia (the gray with the color's CIE L*), each named with its hex value in its tooltip and to screen readers, and taking the keyboard focus; a click or a key on a chip does not apply its color; documentColors shows or hides the row the panel menu's Show Document Colors adds under the wheel or the box: the colors color.used {} lists, headed Selection Colors when something is selected and Document Colors otherwise, most used first and as many as fit in one row (a chip's tooltip gives its hex value and how many times the art uses it; a click applies it to the active proxy or to the selected gradient stop, keeping its color model and its link to a global swatch, or to the selected freeform point, which takes the color alone, and Alt+click applies it to the other proxy; the row reads the colors again when the document or the selection changes, not during a drag, and in art with more than 5,000 color uses at most once every half second after an edit); keys left out or null keep their values ({} reads them), params that are not an object, another key or a value off the list are an error and change nothing, oklch is an error while the active document's RGB space (its assigned profile, else the working RGB space) is not sRGB, the settings are kept with the preferences, and the command does not open the panel (window.panel {panel: \"colorWheel\"} does) (ui.inspect: ui.color_wheel) → {view, channel, sliders, gamut, harmony, harmonyRule, vision, documentColors}", ), ( "ui.savePdfDialog", diff --git a/crates/ui-egui/src/menus/ui_commands.rs b/crates/ui-egui/src/menus/ui_commands.rs index 86d6aedee0..41b089c9e1 100644 --- a/crates/ui-egui/src/menus/ui_commands.rs +++ b/crates/ui-egui/src/menus/ui_commands.rs @@ -1605,7 +1605,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "ui.colorWheel", "Color Wheel Options", "", - "{view?: wheel|box, channel?: hue|saturation|brightness|red|green|blue, sliders?: none|oklch|hsl, gamut?: bool, harmony?: bool, harmonyRule?: complementary|splitComplementary|leftComplement|rightComplement|analogous|analogous2|triad|tetrad|tetrad2|tetrad3|compound|compound2|highContrast|highContrast3|pentagram, vision?: bool, documentColors?: bool} show the Color Wheel panel's wheel or its box, as the panel menu's Wheel View and Box View do, pick the box's channel, as Box Channel does, and show no slider rows under the wheel or the box (none), OKLCH Sliders (oklch) or HSL Sliders (hsl), as the menu items of those names do: the box is a color field with the channel's strip at its right, and the field shows the other two components (hue: saturation across and brightness up; saturation: hue across and brightness up; brightness: hue across and saturation up; red: blue across and green up; green: blue across and red up; blue: red across and green up); OKLCH Sliders edit lightness 0 to 100 %, chroma 0 to 100 % of 0.4 and hue 0 to 360°, CSS Color 4's OKLCH of the display sRGB, and a color outside sRGB keeps L and H and takes the largest chroma that fits at or below the one asked for; HSL Sliders edit hue 0 to 360°, saturation 0 to 100 % and lightness 0 to 100 %, CSS Color 4's HSL of the display sRGB; gamut true grays out the parts of the wheel's square and the box's field whose colors the CMYK space cannot print (the out-of-gamut warning's test, as color.gamutCheck answers it), as Show Out-of-Gamut Colors does, and false shows them again; the shading is approximate: each cell of a 16 by 16 grid over the square or the field is grayed out or not by the color at its center, so a grayed cell can hold printable colors and a clear cell can hold colors that cannot print; harmony shows a marker on the wheel's ring for each other color of harmonyRule (the Color Guide's rule of that id; a rule's label is taken too), as Show Harmony and Harmony Rule do, and a click on a marker applies its color; vision shows Show Color Vision Preview's row under the wheel or the box, four chips with the current color as simulated for protanopia, deuteranopia and tritanopia (the simulations of view.proofSetup's protanopia, deuteranopia and tritanopia targets) and for achromatopsia (the gray with the color's CIE L*), each named with its hex value in its tooltip and to screen readers, and taking the keyboard focus; a click or a key on a chip does not apply its color; documentColors shows or hides the row the panel menu's Show Document Colors adds under the wheel or the box: the colors color.used {} lists, headed Selection Colors when something is selected and Document Colors otherwise, most used first and as many as fit in one row (a chip's tooltip gives its hex value and how many times the art uses it; a click applies it to the active proxy or to the selected gradient stop, keeping its color model and its link to a global swatch, or to the selected freeform point, which takes the color alone, and Alt+click applies it to the other proxy; the row reads the colors again when the document or the selection changes, not during a drag, and in art with more than 5,000 color uses at most once every half second after an edit); keys left out or null keep their values ({} reads them), params that are not an object, another key or a value off the list are an error and change nothing, oklch is an error while the working RGB space is not sRGB, the settings are kept with the preferences, and the command does not open the panel (window.panel {panel: \"colorWheel\"} does) (ui.inspect: ui.color_wheel) → {view, channel, sliders, gamut, harmony, harmonyRule, vision, documentColors}", + "{view?: wheel|box, channel?: hue|saturation|brightness|red|green|blue, sliders?: none|oklch|hsl, gamut?: bool, harmony?: bool, harmonyRule?: complementary|splitComplementary|leftComplement|rightComplement|analogous|analogous2|triad|tetrad|tetrad2|tetrad3|compound|compound2|highContrast|highContrast3|pentagram, vision?: bool, documentColors?: bool} show the Color Wheel panel's wheel or its box, as the panel menu's Wheel View and Box View do, pick the box's channel, as Box Channel does, and show no slider rows under the wheel or the box (none), OKLCH Sliders (oklch) or HSL Sliders (hsl), as the menu items of those names do: the box is a color field with the channel's strip at its right, and the field shows the other two components (hue: saturation across and brightness up; saturation: hue across and brightness up; brightness: hue across and saturation up; red: blue across and green up; green: blue across and red up; blue: red across and green up); OKLCH Sliders edit lightness 0 to 100 %, chroma 0 to 100 % of 0.4 and hue 0 to 360°, CSS Color 4's OKLCH of the display sRGB, and a color outside sRGB keeps L and H and takes the largest chroma that fits at or below the one asked for; HSL Sliders edit hue 0 to 360°, saturation 0 to 100 % and lightness 0 to 100 %, CSS Color 4's HSL of the display sRGB; gamut true grays out the parts of the wheel's square and the box's field whose colors the CMYK space cannot print (the out-of-gamut warning's test, as color.gamutCheck answers it), as Show Out-of-Gamut Colors does, and false shows them again; the shading is approximate: each cell of a 16 by 16 grid over the square or the field is grayed out or not by the color at its center, so a grayed cell can hold printable colors and a clear cell can hold colors that cannot print; harmony shows a marker on the wheel's ring for each other color of harmonyRule (the Color Guide's rule of that id; a rule's label is taken too), as Show Harmony and Harmony Rule do, and a click on a marker applies its color; vision shows Show Color Vision Preview's row under the wheel or the box, four chips with the current color as simulated for protanopia, deuteranopia and tritanopia (the simulations of view.proofSetup's protanopia, deuteranopia and tritanopia targets) and for achromatopsia (the gray with the color's CIE L*), each named with its hex value in its tooltip and to screen readers, and taking the keyboard focus; a click or a key on a chip does not apply its color; documentColors shows or hides the row the panel menu's Show Document Colors adds under the wheel or the box: the colors color.used {} lists, headed Selection Colors when something is selected and Document Colors otherwise, most used first and as many as fit in one row (a chip's tooltip gives its hex value and how many times the art uses it; a click applies it to the active proxy or to the selected gradient stop, keeping its color model and its link to a global swatch, or to the selected freeform point, which takes the color alone, and Alt+click applies it to the other proxy; the row reads the colors again when the document or the selection changes, not during a drag, and in art with more than 5,000 color uses at most once every half second after an edit); keys left out or null keep their values ({} reads them), params that are not an object, another key or a value off the list are an error and change nothing, oklch is an error while the active document's RGB space (its assigned profile, else the working RGB space) is not sRGB, the settings are kept with the preferences, and the command does not open the panel (window.panel {panel: \"colorWheel\"} does) (ui.inspect: ui.color_wheel) → {view, channel, sliders, gamut, harmony, harmonyRule, vision, documentColors}", ), ( "ui.savePdfDialog", From c46bdce70687f8944f72699f330d29241dc1e39d Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 19 Nov 2026 20:35:48 -0800 Subject: [PATCH 010/151] Color Wheel: a remembered pick ends with the document's undo step MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The remembered HSB, OKLCH and HSL now also belong to the document's undo step. Another edit, an Undo or a Redo drops them, also when the slider rows are hidden and the same color comes back before they show again. docs/mcp.md: color.convert to oklch answers an object with model "oklch" and values [L %, C, H°]. --- crates/ui-egui/src/panels/color_wheel.rs | 9 ++++++-- .../ui-egui/src/panels/tests_color_wheel.rs | 22 +++++++++++++++++++ docs/mcp.md | 3 ++- 3 files changed, 31 insertions(+), 3 deletions(-) diff --git a/crates/ui-egui/src/panels/color_wheel.rs b/crates/ui-egui/src/panels/color_wheel.rs index c34946387c..f38c35dfa9 100644 --- a/crates/ui-egui/src/panels/color_wheel.rs +++ b/crates/ui-egui/src/panels/color_wheel.rs @@ -710,11 +710,15 @@ fn vision_row(ui: &mut Ui, cms: &Cms, color: Option<&Color>) { } /// What the HSB picked last belongs to: the document, the selected objects or text characters, -/// the appearance item, the proxy, the gradient stop or freeform point, its paint, and the color -/// the pick stored. The wheel shows that HSB only while all of them are unchanged. +/// the appearance item, the proxy, the gradient stop or freeform point, its paint, the color the +/// pick stored, and the document's undo step. The wheel shows that HSB only while all of them are +/// unchanged. #[derive(Clone, Debug, PartialEq)] struct Owner { doc: Option, + /// The document's [`History::step`](vectorcraft_engine::History::step): another edit, an Undo + /// or a Redo changes it, also when the same color comes back. + step: Option<(u64, u64)>, selection: Vec, /// The Type tool's selected characters, when it edits the paint. text_selection: Option<(NodeId, usize, usize)>, @@ -738,6 +742,7 @@ impl Owner { }; Self { doc: st.map(|d| d.uid), + step: st.map(|d| d.history.step()), selection: st.map(|d| d.selection.objects.clone()).unwrap_or_default(), text_selection: super::character::text_editing(app), appearance_item: app.session.appearance_item(), diff --git a/crates/ui-egui/src/panels/tests_color_wheel.rs b/crates/ui-egui/src/panels/tests_color_wheel.rs index 2c86f073c5..16538de82f 100644 --- a/crates/ui-egui/src/panels/tests_color_wheel.rs +++ b/crates/ui-egui/src/panels/tests_color_wheel.rs @@ -1169,6 +1169,28 @@ fn a_remembered_hue_is_dropped_after_the_paint_changes() { } } +/// The hue given to a gray is also dropped when the paint changes and comes back while the rows are +/// hidden, so showing the rows again shows the gray's own hue, 0°. +#[test] +fn a_remembered_hue_is_dropped_after_the_paint_changes_while_the_rows_are_hidden() { + for (rows, hue) in [("hsl", "HSL Hue"), ("oklch", "Hue")] { + let mut app = app(json!("#808080")); + app.run("ui.colorWheel", json!({"sliders": rows})).unwrap(); + let mut h = oklch_harness_shown(app); + set_slider_value(&mut h, hue, 240.0); + assert_eq!(oklch_slider(&h, hue).accesskit_node().numeric_value(), Some(240.0), "{rows}"); + h.state_mut().run("ui.colorWheel", json!({"sliders": "none"})).unwrap(); + h.run_steps(2); + h.state_mut().run("paint.setFill", json!({"color": "#ff0000"})).unwrap(); + h.run_steps(2); + h.state_mut().run("paint.setFill", json!({"color": "#808080"})).unwrap(); + h.run_steps(2); + h.state_mut().run("ui.colorWheel", json!({"sliders": rows})).unwrap(); + h.run_steps(2); + assert_eq!(oklch_slider(&h, hue).accesskit_node().numeric_value(), Some(0.0), "{rows}: the gray's own hue"); + } +} + /// Hiding the rows, or showing the other rows, during a drag on a row keeps the color the drag /// previewed as one undo step and leaves no interaction open. #[test] diff --git a/docs/mcp.md b/docs/mcp.md index 2a3ad79bdb..b65d1c1ab5 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -702,7 +702,8 @@ the box), and `"none"` hides them in any RGB space. `"oklch"` is an error while not sRGB: the profile assigned to the document when it has one, else the working RGB space of Edit › Color Settings. `ui.colorWheel {"sliders": "hsl"}` shows HSL Sliders in their place: H, S and L rows with the hue (0 to 360°), saturation and lightness (0 to 100 %) of the color's display sRGB, as CSS Color 4's `hsl()` defines them. -`color.convert {"color": "#ff0000", "to": "oklch"}` answers the color's OKLCH as `[L %, C, H°]` of its display sRGB. +`color.convert {"color": "#ff0000", "to": "oklch"}` answers the color's OKLCH of its display sRGB in an object with +`model: "oklch"` and `values: [L %, C, H°]`, next to the `hex`, `lab`, `outOfGamut` and `deltaE` of every conversion. A color outside sRGB (a Lab or CMYK color, an RGB color in a wider RGB space, or RGB numbers past 0 to 1) is clipped to sRGB first. The answer of `ui.colorWheel` and the settings also carry `sliders`. From 00ac5d7a3f3a98cd037f48c1381ffe7b743aa44c Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 19 Nov 2026 19:13:56 -0800 Subject: [PATCH 011/151] Retype: installed fonts that are not loaded yet are matched too Shapes no loaded font matches are now compared with the installed fonts that nothing has loaded yet. type.retype reads their files one at a time, smallest first, until each such shape matches a font it has read, and type.retypeFonts (the Retype panel's list) ranks the matching installed fonts with the loaded ones, up to 96 fonts in all. - A file is read for the search and released. A face whose glyphs match is loaded as it was read, without the family's other files, and later searches in every open document compare it ahead of the other loaded faces. A matching face that another version of the same family and style shadows is loaded and not listed. - Files over 256 MiB, and the files and faces past 2 GiB read or 500,000 glyphs drawn, are left out and counted in the result's installed.skipped. - A plain shape (one contour of up to four straight edges, such as a rectangle or a hyphen) does not start the search, and matches only a font the other shapes found. - installed: false turns the search off; any value other than true, false or null is an error. retype.find takes installed too. - In the app, Type > Retype and Find Matching Fonts (the panel's button, or retype.find from a menu or the command palette) search on a thread of their own. After 0.4 seconds a progress window shows the files read, with Cancel (also Esc, retype.cancelSearch). When the search is done the command runs with the fonts it found, without reading the installed fonts again, unless the document or its selection changed meanwhile. Reset Retype Panel and a new search stop a panel search. An MCP cancel stops the search between files. Part of #4934. --- crates/engine/src/cmd.rs | 3 + crates/engine/src/cmd/retype.rs | 100 ++++- crates/engine/src/cmd/retype_fonts.rs | 139 ++++--- crates/engine/src/cmd/retype_fonts_tests.rs | 60 ++- crates/engine/src/cmd/retype_installed.rs | 363 ++++++++++++++++++ .../engine/src/cmd/retype_installed_tests.rs | 359 +++++++++++++++++ crates/engine/src/cmd/retype_tests.rs | 10 +- crates/engine/src/lib.rs | 3 + crates/engine/src/session/documents.rs | 1 + crates/text/src/fontdb.rs | 2 + crates/text/src/fontdb/installed.rs | 167 ++++++++ crates/text/src/lib.rs | 2 +- crates/text/src/retype.rs | 125 +++++- crates/ui-egui/src/app.rs | 8 +- 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 + crates/ui-egui/src/lib.rs | 3 + crates/ui-egui/src/menus/invoke.rs | 15 + crates/ui-egui/src/menus/run.rs | 1 + crates/ui-egui/src/menus/state.rs | 1 + crates/ui-egui/src/menus/ui_commands.rs | 8 +- crates/ui-egui/src/opening.rs | 1 + crates/ui-egui/src/palette.rs | 1 + crates/ui-egui/src/panels/retype.rs | 51 ++- crates/ui-egui/src/panels/retype/tests.rs | 13 +- crates/ui-egui/src/retype_runs.rs | 249 ++++++++++++ crates/ui-egui/src/tests.rs | 1 + crates/ui-egui/src/tests/retype_runs.rs | 191 +++++++++ docs/gaps.md | 2 +- docs/mcp.md | 54 ++- docs/target-app-parity.md | 6 +- docs/type-parity.md | 2 +- docs/ui-parity.md | 2 +- 56 files changed, 1891 insertions(+), 102 deletions(-) create mode 100644 crates/engine/src/cmd/retype_installed.rs create mode 100644 crates/engine/src/cmd/retype_installed_tests.rs create mode 100644 crates/text/src/fontdb/installed.rs create mode 100644 crates/ui-egui/src/retype_runs.rs create mode 100644 crates/ui-egui/src/tests/retype_runs.rs diff --git a/crates/engine/src/cmd.rs b/crates/engine/src/cmd.rs index 4f0d2bad63..25b8a88c13 100644 --- a/crates/engine/src/cmd.rs +++ b/crates/engine/src/cmd.rs @@ -918,6 +918,9 @@ pub use buildcmds::{TRACE_PRESET_EXTS, TRACE_PRESET_FORMAT, TRACE_PRESET_MAX_BYT /// An Image Trace made off the UI thread, and what it traced (#3098). pub use buildcmds::{TraceRun, Traced, image_trace_target}; +/// Retype's search of the installed fonts, made off the UI thread. +pub use retype::{RetypeFound, RetypeRun, RetypeSearch}; + /// The saved Image Trace presets' revision and latest changes ([`crate::Session`] keeps them). pub(crate) use buildcmds::TracePresetChanges; diff --git a/crates/engine/src/cmd/retype.rs b/crates/engine/src/cmd/retype.rs index 0e31d5632a..9cef3250e9 100644 --- a/crates/engine/src/cmd/retype.rs +++ b/crates/engine/src/cmd/retype.rs @@ -41,7 +41,7 @@ pub fn specs() -> Vec { "Retype", ["Type"], None, - "{fonts?: [family…]} turn the selected outlined text (glyph paths and compound paths, inside groups too) back into live type: each shape is matched against the glyphs of the fonts the app has loaded, the document's fonts and the families in fonts, the same up to uniform scale, rotation and translation (exact matches only); matched glyphs become point text in that font and size at the same baseline, one object per line unless lines stack into one (below), with the first glyph's fill, stroke, opacity and blend mode, in one undo step; a line of three or more glyphs takes the spacing most of its gaps share as its tracking (pair kerning left out) when tracked type draws all of it in place, or more of it than untracked type (when untracked type also draws it, untracked type is kept if the tracking is under one unit or the tracked type would drop a gap one space wide (a b c keeps its spaces), and the tracked type otherwise), and negative tracking only when the line is opaque, Normal, with a solid fill or none and no stroke (its glyphs may overlap); lines that follow each other in paint order with the same group, paint, font, size, turn and tracking (an untracked line of one or two glyphs takes the others' tracking), each one the same leading (0.25 to 3 times the size) below the one before, and lined up at their starts, ends or centers become one area type object with that leading (Auto when Auto gives it) and left, right or center alignment, or one multi-line point type object when area type (after Text Wrap) would not draw the outlines' glyphs in their places or when checking the Text Wrap objects on the changed layers would copy more than 2,000,000 anchors, subpaths and shapes; where even that type would move a glyph, the lines before that glyph's line stay one object and the rest are joined again from that line; lines with an opacity below 100%, a blend mode other than Normal, a gradient or pattern fill or a stroke stay one object each; a line splits where its type would not draw the outlines' glyphs in their places (uneven spacing, manual kerning, font substitutions); shapes that match no font, glyphs type cannot draw as they are, and shapes with their own opacity mask stay as they are → {ids (the new type), texts (lines joined by \\n), fonts: [{family, style, size, tracking (1/1000 em), leading (pt, null for Auto or one line), area (bool)}], unmatched: [id…], truncated (shapes past the limits of 2048 shapes or 16 nested groups were left out)}; an error when no shape matches", + "{fonts?: [family…], installed?: bool} turn the selected outlined text (glyph paths and compound paths, inside groups too) back into live type: each shape is matched against the glyphs of the fonts the app has loaded, the document's fonts and the families in fonts, the same up to uniform scale, rotation and translation (exact matches only); shapes none of those match are then compared with the installed fonts not loaded yet, unless installed is false (true, omitted or null: compared): their files are read smallest first, one at a time, until each such shape matches a font read, leaving out files over 256 MiB and the files and faces past 2 GiB read or 500,000 glyphs drawn in all, and a font whose glyphs match is loaded; a plain shape (one contour of up to four straight edges, such as a rectangle) starts no such reading and matches only a font the other shapes found; a cancel stops between files; matched glyphs become point text in that font and size at the same baseline, one object per line unless lines stack into one (below), with the first glyph's fill, stroke, opacity and blend mode, in one undo step; a line of three or more glyphs takes the spacing most of its gaps share as its tracking (pair kerning left out) when tracked type draws all of it in place, or more of it than untracked type (when untracked type also draws it, untracked type is kept if the tracking is under one unit or the tracked type would drop a gap one space wide (a b c keeps its spaces), and the tracked type otherwise), and negative tracking only when the line is opaque, Normal, with a solid fill or none and no stroke (its glyphs may overlap); lines that follow each other in paint order with the same group, paint, font, size, turn and tracking (an untracked line of one or two glyphs takes the others' tracking), each one the same leading (0.25 to 3 times the size) below the one before, and lined up at their starts, ends or centers become one area type object with that leading (Auto when Auto gives it) and left, right or center alignment, or one multi-line point type object when area type (after Text Wrap) would not draw the outlines' glyphs in their places or when checking the Text Wrap objects on the changed layers would copy more than 2,000,000 anchors, subpaths and shapes; where even that type would move a glyph, the lines before that glyph's line stay one object and the rest are joined again from that line; lines with an opacity below 100%, a blend mode other than Normal, a gradient or pattern fill or a stroke stay one object each; a line splits where its type would not draw the outlines' glyphs in their places (uneven spacing, manual kerning, font substitutions); shapes that match no font, glyphs type cannot draw as they are, and shapes with their own opacity mask stay as they are → {ids (the new type), texts (lines joined by \\n), fonts: [{family, style, size, tracking (1/1000 em), leading (pt, null for Auto or one line), area (bool)}], unmatched: [id…], truncated (shapes past the limits of 2048 shapes or 16 nested groups were left out), installed: {read (installed faces compared), skipped (installed faces those limits left out)}}; an error when no shape matches, and when installed is not true, false or null", has_selected_path, retype )] @@ -49,6 +49,10 @@ pub fn specs() -> Vec { #[path = "retype_fonts.rs"] pub(super) mod fonts; +#[path = "retype_installed.rs"] +mod installed; + +pub use installed::{RetypeFound, RetypeRun, RetypeSearch}; /// A shape to match: a path or compound path, in document space. struct Piece { @@ -126,7 +130,8 @@ fn type_can_paint(ap: &Appearance) -> bool { ap.is_basic() && ap.stroke().is_none_or(|s| s.start_arrow.is_none() && s.end_arrow.is_none() && s.profile.is_none() && s.brush.is_none()) } -/// The faces to match against: the families in `fonts`, the document's fonts, then every loaded face. +/// The faces to match against: the families in `fonts`, the document's fonts, the faces earlier +/// searches of the installed fonts loaded ([`installed::found`]), then every other loaded face. fn candidate_faces(db: &FontDb, d: &Document, fonts: &[String]) -> Vec> { let mut families: Vec = fonts.iter().take(MAX_FONT_PARAMS).cloned().collect(); d.walk(|n| { @@ -153,7 +158,8 @@ fn candidate_faces(db: &FontDb, d: &Document, fonts: &[String]) -> Vec= cap { break; } @@ -1079,19 +1085,45 @@ fn new_line(pc: &Piece, cands: &[GlyphMatch]) -> Option { }) } +/// `type.retype`'s `fonts` param: the family names it lists. +fn fonts_param(p: &Value) -> Result> { + const C: &str = "type.retype"; + match p.get("fonts") { + None | Some(Value::Null) => Ok(vec![]), + Some(Value::Array(a)) => { + a.iter().map(|v| v.as_str().map(str::to_owned).ok_or_else(|| bad(C, "fonts must be a list of family names"))).collect() + } + Some(_) => Err(bad(C, "fonts must be a list of family names")), + } +} + +/// The shapes of the selected objects, in paint order, and whether shapes past the limits were +/// left out; an error when the selection holds none. +fn selected_pieces(s: &Session) -> Result<(Vec, bool)> { + let roots = selected_roots(s)?; + let d = &s.doc()?.doc; + let mut pieces = vec![]; + let (mut barrier, mut truncated) = (true, false); + for r in &roots { + if let Some(n) = d.node(*r) { + collect(n, d.parent_of(*r), 0, &mut barrier, &mut truncated, &mut pieces); + } + } + if pieces.is_empty() { + return Err(EngineError::Other("Retype: select outlined text (paths or compound paths)".into())); + } + Ok((pieces, truncated)) +} + fn retype(s: &mut Session, p: &Value) -> Result { const C: &str = "type.retype"; - let fonts: Vec = match p.get("fonts") { - None | Some(Value::Null) => vec![], - Some(Value::Array(a)) => { - a.iter().map(|v| v.as_str().map(str::to_owned).ok_or_else(|| bad(C, "fonts must be a list of family names"))).collect::>()? - } - Some(_) => return Err(bad(C, "fonts must be a list of family names")), - }; + let fonts = fonts_param(p)?; + let search_installed = installed::wanted(C, p)?; + let handed = installed::handed(s); let roots = selected_roots(s)?; let db = FontDb::global(); let system_layout = s.doc()?.doc.setup.system_layout; - let (lines, unmatched, truncated) = { + let (lines, unmatched, truncated, installed) = { let d = &s.doc()?.doc; let mut pieces = vec![]; let mut truncated = false; @@ -1119,8 +1151,20 @@ fn retype(s: &mut Session, p: &Value) -> Result { let wanted: std::collections::BTreeSet = pieces.iter().filter(|pc| !pc.keeps_outline).filter_map(|pc| vectorcraft_text::retype::shape_key(&pc.path)).collect(); // Nothing to match (every shape stays an outline): no font is read. - let index = if wanted.is_empty() { RetypeIndex::default() } else { RetypeIndex::build(db, candidate_faces(db, d, &fonts), &wanted) }; - let found: Vec> = pieces.iter().map(|pc| if pc.keeps_outline { vec![] } else { index.matches(&pc.path) }).collect(); + let cands = if wanted.is_empty() { vec![] } else { candidate_faces(db, d, &fonts) }; + let compared: Vec = cands.iter().map(|f| f.id()).collect(); + let index = if wanted.is_empty() { RetypeIndex::default() } else { RetypeIndex::build(db, cands, &wanted) }; + let mut found: Vec> = pieces.iter().map(|pc| if pc.keeps_outline { vec![] } else { index.matches(&pc.path) }).collect(); + // Shapes no face matched are compared with the installed fonts not loaded yet, or with + // what a search made off the UI thread found for them. + let installed = match handed { + Some(handed) => { + add_installed(db, &pieces, &mut found, &handed, &compared); + handed + } + None if search_installed => from_installed(db, &pieces, &mut found)?, + None => installed::Installed::default(), + }; // The face most shapes match, so a glyph several fonts share is set in the same font as // the glyphs around it. let mut votes: Vec<(u32, usize)> = vec![]; @@ -1194,7 +1238,7 @@ fn retype(s: &mut Session, p: &Value) -> Result { // Joining lines takes at most four tries' work per glyph (see [`Block::made`]), with room // for small blocks. let mut budget = lines.iter().map(|l| l.pieces.len()).fold(0usize, usize::saturating_add).saturating_mul(24).saturating_add(256); - (blocks(lines, follows, system_layout, &mut budget), unmatched, truncated) + (blocks(lines, follows, system_layout, &mut budget), unmatched, truncated, installed) }; if lines.is_empty() { return Err(EngineError::Other(format!("Retype: no selected shape matches a glyph of an available font ({} checked)", unmatched.len()))); @@ -1317,9 +1361,37 @@ fn retype(s: &mut Session, p: &Value) -> Result { .collect::>(), "unmatched": unmatched.iter().map(|i| i.0).collect::>(), "truncated": truncated, + "installed": installed.json(), })) } +/// Look for the shapes of `pieces` that `found` holds no glyph for (and that may become type) in +/// the installed faces not loaded yet ([`installed::search`], which plain shapes do not start). +/// Every shape that may become type then also gets its matches in the faces found, after the ones +/// `found` holds. +fn from_installed(db: &FontDb, pieces: &[Piece], found: &mut [Vec]) -> Result { + let left: Vec<&BezPath> = pieces.iter().zip(found.iter()).filter(|(pc, ms)| !pc.keeps_outline && ms.is_empty()).map(|(pc, _)| &pc.path).collect(); + let installed = installed::search(db, &left, false)?; + add_installed(db, pieces, found, &installed, &[]); + Ok(installed) +} + +/// Gives every shape of `pieces` that may become type its matches in the faces `installed` found, +/// after the ones `found` holds, leaving out the faces of `compared` (the faces `found` comes +/// from), whose matches it holds already. +fn add_installed(db: &FontDb, pieces: &[Piece], found: &mut [Vec], installed: &installed::Installed, compared: &[u32]) { + let faces: Vec<_> = installed.faces.iter().filter(|f| !compared.contains(&f.id())).cloned().collect(); + if faces.is_empty() { + return; + } + let keys: std::collections::BTreeSet = + pieces.iter().filter(|pc| !pc.keeps_outline).filter_map(|pc| vectorcraft_text::retype::shape_key(&pc.path)).collect(); + let index = RetypeIndex::build(db, faces, &keys); + for (pc, ms) in pieces.iter().zip(found.iter_mut()).filter(|(pc, _)| !pc.keeps_outline) { + ms.extend(index.matches(&pc.path)); + } +} + #[cfg(test)] #[path = "retype_tests.rs"] mod tests; diff --git a/crates/engine/src/cmd/retype_fonts.rs b/crates/engine/src/cmd/retype_fonts.rs index dc9a413d5f..bdbceb57a2 100644 --- a/crates/engine/src/cmd/retype_fonts.rs +++ b/crates/engine/src/cmd/retype_fonts.rs @@ -3,22 +3,25 @@ //! (, //! ). //! The panel lists ten fonts and five more on request. Each selected glyph shape is compared with -//! the glyphs of up to 96 loaded fonts, those of the document's live type first, by the same -//! matching as `type.retype` (exact matches only). Of two versions of one font, only the version its +//! the glyphs of up to 96 loaded fonts, those of the document's live type first, and of the +//! installed fonts not loaded yet (`retype_installed.rs`), by the same matching as `type.retype` +//! (exact matches only). Of two versions of one font, only the version its //! family and style name gives is compared. The order is VectorCraft's own: a font ranks by how many -//! of the shapes it matches, then by how closely, on average, and then by name. The query changes -//! nothing. +//! of the shapes it matches, then by how closely, on average, and then by name. The query does not +//! change the document; the installed fonts that match are loaded. use std::collections::BTreeSet; use std::sync::Arc; +use kurbo::BezPath; use serde_json::{Value, json}; -use vectorcraft_text::FontDb; +use vectorcraft_doc::Document; use vectorcraft_text::retype::{RetypeIndex, shape_key}; +use vectorcraft_text::{FontDb, FontFace}; -use super::super::edit::selected_roots; -use super::super::{CommandSpec, EngineError, Result, Session, bad, cmd, has_selected_path}; -use super::{candidate_faces, collect}; +use super::super::{CommandSpec, Result, Session, bad, cmd, has_selected_path}; +use super::installed::Installed; +use super::{candidate_faces, selected_pieces}; pub(in crate::cmd) fn specs() -> Vec { vec![cmd!( @@ -26,7 +29,7 @@ pub(in crate::cmd) fn specs() -> Vec { "Find Matching Fonts", [], None, - "{count?: 1..96 (default 10)} the fonts whose glyphs match the selected outlined text, as the Retype panel lists them: each selected shape (paths and compound paths, inside groups too) is compared with the glyphs of up to 96 loaded fonts, those of the document's live type first, by type.retype's matching (exact matches only); of two versions of a font loaded at once, only the version its family and style name gives is compared, the one choosing the font sets; the fonts rank by how many shapes each matches, then by the mean distance left after fitting, then by family and style name; the document does not change → {fonts: [{family, style, matched (shapes it matches)}] (the first count), shapes (shapes compared), more (more fonts match than count), truncated (shapes past the limits were left out)}; a count that is not a whole number from 1 to 96 is an error", + "{count?: 1..96 (default 10), installed?: bool} the fonts whose glyphs match the selected outlined text, as the Retype panel lists them: each selected shape (paths and compound paths, inside groups too) is compared with the glyphs of up to 96 loaded fonts, those of the document's live type first, by type.retype's matching (exact matches only), and, unless installed is false (true, omitted or null: compared), with the installed fonts not loaded yet, within type.retype's limits on reading them (every file within them is read, and the fonts that match are loaded while the list holds fewer than 96 fonts, loaded ones included); of two versions of a font, only the version its family and style name gives is compared, the one choosing the font sets; the fonts rank by how many shapes each matches, then by the mean distance left after fitting, then by family and style name; the document does not change → {fonts: [{family, style, matched (shapes it matches)}] (the first count), shapes (shapes compared), more (more fonts match than count), truncated (shapes past the limits were left out), installed: {read, skipped} (as type.retype reports them)}; a count that is not a whole number from 1 to 96, or an installed that is not true, false or null, is an error", has_selected_path, retype_fonts )] @@ -38,7 +41,7 @@ pub(super) const DEFAULT_COUNT: usize = 10; pub(super) const MAX_COUNT: usize = vectorcraft_text::retype::MAX_FACES; /// One font that matched some of the shapes. -struct Ranked { +pub(super) struct Ranked { face: Arc, /// How many shapes it matched. matched: usize, @@ -52,57 +55,85 @@ impl Ranked { } } -pub(super) fn retype_fonts(s: &mut Session, p: &Value) -> Result { - retype_fonts_in(s, p, FontDb::global()) -} - -/// [`retype_fonts`] with the fonts of `db`. -fn retype_fonts_in(s: &mut Session, p: &Value, db: &FontDb) -> Result { - const C: &str = "type.retypeFonts"; - let count = match p.get("count") { - None | Some(Value::Null) => DEFAULT_COUNT, +/// The `count` param: how many fonts to list. +pub(super) fn count_param(p: &Value) -> Result { + match p.get("count") { + None | Some(Value::Null) => Ok(DEFAULT_COUNT), Some(v) => v .as_u64() .and_then(|n| usize::try_from(n).ok()) .filter(|n| (1..=MAX_COUNT).contains(n)) - .ok_or_else(|| bad(C, "`count` must be a whole number from 1 to 96"))?, - }; - let roots = selected_roots(s)?; - let d = &s.doc()?.doc; - let mut pieces = vec![]; - let (mut barrier, mut truncated) = (true, false); - for r in &roots { - if let Some(n) = d.node(*r) { - collect(n, d.parent_of(*r), 0, &mut barrier, &mut truncated, &mut pieces); - } + .ok_or_else(|| bad("type.retypeFonts", "`count` must be a whole number from 1 to 96")), } - if pieces.is_empty() { - return Err(EngineError::Other("Retype: select outlined text (paths or compound paths)".into())); - } - // Only glyphs with a selected shape's key (segments per contour) can match one. - let wanted: BTreeSet = pieces.iter().filter_map(|pc| shape_key(&pc.path)).collect(); - // A font is chosen by its family and style, which set the version the name gives: of two - // versions of one font, only that one is compared. The other versions do not take the places - // of fonts loaded after them. - let by_name = |f: &Arc| db.face(&f.family, &f.style).is_some_and(|g| g.id() == f.id()); - let mut faces: Vec<_> = candidate_faces(db, d, &[]).into_iter().filter(by_name).collect(); +} + +/// Is `f` the version of its font that its family and style name gives? A font is chosen by its +/// family and style, which set that version: of two versions of one font, only that one is +/// compared, and the other versions do not take the places of fonts loaded after them. +fn by_name(db: &FontDb, f: &FontFace) -> bool { + db.face(&f.family, &f.style).is_some_and(|g| g.id() == f.id()) +} + +/// The loaded faces the list compares: those of the document's live type first, then the other +/// loaded faces, each the version its name gives, at most [`MAX_COUNT`]. +pub(super) fn listed_faces(db: &FontDb, d: &Document) -> Vec> { + let mut faces: Vec<_> = candidate_faces(db, d, &[]).into_iter().filter(|f| by_name(db, f)).collect(); for f in db.loaded_faces() { - if faces.len() >= vectorcraft_text::retype::MAX_FACES { + if faces.len() >= MAX_COUNT { break; } - if by_name(&f) && !faces.iter().any(|k| k.id() == f.id()) { + if by_name(db, &f) && !faces.iter().any(|k| k.id() == f.id()) { faces.push(f); } } + faces +} + +/// The fonts of `faces` whose glyphs match `shapes`, unranked, and with `search_installed` those of +/// the installed fonts not loaded yet, for the places left of [`MAX_COUNT`] (loading the ones that +/// match), with what that search read. With `handed` (what a search made off the UI thread found, +/// [`super::installed::RetypeFound`]) its faces are ranked instead, and the installed fonts are not +/// read again. +pub(super) fn rank_fonts( + db: &FontDb, + faces: Vec>, + shapes: &[&BezPath], + search_installed: bool, + handed: Option, +) -> Result<(Vec, Installed)> { + // Only glyphs with a selected shape's key (segments per contour) can match one. + let wanted: BTreeSet = shapes.iter().filter_map(|s| shape_key(s)).collect(); // No shape has a key: no font is read. let index = if wanted.is_empty() { RetypeIndex::default() } else { RetypeIndex::build(db, faces, &wanted) }; - // A shape's paint does not change which glyph it is: shapes that would stay outlines count too. let mut ranked: Vec = vec![]; - for pc in &pieces { + rank(&index, shapes, &mut ranked); + // The installed fonts not loaded yet: those whose glyphs match a shape, of the version their + // family and style name gives, up to 96 fonts listed in all. + let room = MAX_COUNT.saturating_sub(ranked.len()); + let found = if let Some(handed) = handed { + handed + } else if !search_installed { + Installed::default() + } else if room == 0 { + Installed { skipped: db.unloaded_installed_faces().len(), ..Default::default() } + } else { + super::installed::search_listed(db, shapes, room, &|f| by_name(db, f))? + }; + // A face found earlier (handed in) may be loaded and ranked already: it counts once. + let more: Vec<_> = found.faces.iter().filter(|f| !ranked.iter().any(|r| r.face.id() == f.id())).cloned().collect(); + if !more.is_empty() { + rank(&RetypeIndex::build(db, more, &wanted), shapes, &mut ranked); + } + Ok((ranked, found)) +} + +/// Adds to `ranked` the fonts of `index` that match `shapes`. +fn rank(index: &RetypeIndex, shapes: &[&BezPath], ranked: &mut Vec) { + for shape in shapes { // A shape can fit several glyphs or poses of one font: it counts once for the font, at its // closest fit. - let mut best: Vec<(Arc, f64)> = vec![]; - for m in index.all_matches(&pc.path) { + let mut best: Vec<(Arc, f64)> = vec![]; + for m in index.all_matches(shape) { match best.iter_mut().find(|(f, _)| f.id() == m.face.id()) { Some(b) => b.1 = b.1.min(m.residual), None => best.push((m.face, m.residual)), @@ -118,6 +149,23 @@ fn retype_fonts_in(s: &mut Session, p: &Value, db: &FontDb) -> Result { } } } +} + +pub(super) fn retype_fonts(s: &mut Session, p: &Value) -> Result { + retype_fonts_in(s, p, FontDb::global()) +} + +/// [`retype_fonts`] with the fonts of `db`. +fn retype_fonts_in(s: &mut Session, p: &Value, db: &FontDb) -> Result { + const C: &str = "type.retypeFonts"; + let count = count_param(p)?; + let search_installed = super::installed::wanted(C, p)?; + let handed = super::installed::handed(s); + let (pieces, truncated) = selected_pieces(s)?; + let d = &s.doc()?.doc; + // A shape's paint does not change which glyph it is: shapes that would stay outlines count too. + let shapes: Vec<&BezPath> = pieces.iter().map(|pc| &pc.path).collect(); + let (mut ranked, found) = rank_fonts(db, listed_faces(db, d), &shapes, search_installed, handed)?; ranked.sort_by(|a, b| { b.matched .cmp(&a.matched) @@ -133,6 +181,7 @@ fn retype_fonts_in(s: &mut Session, p: &Value, db: &FontDb) -> Result { "shapes": pieces.len(), "more": more, "truncated": truncated, + "installed": found.json(), })) } diff --git a/crates/engine/src/cmd/retype_fonts_tests.rs b/crates/engine/src/cmd/retype_fonts_tests.rs index d7e675f503..c660fd3e74 100644 --- a/crates/engine/src/cmd/retype_fonts_tests.rs +++ b/crates/engine/src/cmd/retype_fonts_tests.rs @@ -99,7 +99,7 @@ fn shapes_that_are_no_glyph_list_no_font() { let rect = s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 80, "height": 40})).unwrap()["id"].as_u64().unwrap(); s.execute("select.set", &json!({"ids": [rect]})).unwrap(); let r = query(&mut s, json!({}), bundled()); - assert_eq!(r, json!({"fonts": [], "shapes": 1, "more": false, "truncated": false})); + assert_eq!(r, json!({"fonts": [], "shapes": 1, "more": false, "truncated": false, "installed": {"read": 0, "skipped": 0}})); // Live type alone holds no shape to compare. let t = s.execute("text.create", &json!({"x": 10, "y": 100, "text": "live"})).unwrap()["id"].as_u64().unwrap(); s.execute("select.set", &json!({"ids": [t]})).unwrap(); @@ -146,6 +146,64 @@ fn of_two_versions_only_the_one_the_name_gives_is_listed() { assert_eq!(names(&r).iter().filter(|f| f.0 == FAMILY).count(), 1, "version 1 matches and is listed once: {r}"); } +#[test] +fn installed_fonts_not_loaded_are_ranked_too_unless_left_out() { + use vectorcraft_text::test_fonts::named_copy; + let dir = vectorcraft_testkit::temp_dir("retype-fonts-installed"); + let file = dir.join("RetypeListed-Regular.ttf"); + std::fs::write(&file, named_copy(true, ("Retype Listed", "Regular", "Version 1.000", "RetypeListed-Regular")).unwrap()).unwrap(); + let db = FontDb::with_font_dirs(vec![dir]); + let mut s = session(); + let inter = outlined(&mut s, json!({"x": 40, "y": 100, "text": "Kgw", "size": 40, "font": "Inter", "style": "Regular"})); + s.execute("select.set", &json!({"ids": [inter]})).unwrap(); + // Left out: the installed copy is not read, and stays unloaded. + let r = query(&mut s, json!({"count": 96, "installed": false}), &db); + assert!(!names(&r).iter().any(|f| f.0 == "Retype Listed"), "{r}"); + assert_eq!(r["installed"], json!({"read": 0, "skipped": 0}), "{r}"); + assert!(db.unloaded_installed_faces().iter().any(|f| f.family == "Retype Listed")); + // Compared: the copy of Inter matches every shape, as Inter does, and is loaded. + let r = query(&mut s, json!({"count": 96}), &db); + let fonts = names(&r); + assert!(fonts.contains(&("Retype Listed".to_string(), "Regular".to_string(), 3)), "{r}"); + assert!(fonts.contains(&("Inter".to_string(), "Regular".to_string(), 3)), "{r}"); + assert_eq!(r["installed"], json!({"read": 1, "skipped": 0}), "{r}"); + assert!(!db.unloaded_installed_faces().iter().any(|f| f.family == "Retype Listed")); +} + +#[test] +fn installed_fonts_fill_the_list_up_to_96_fonts_in_all() { + use vectorcraft_text::test_fonts::named_copy; + let copy = |family: &str| { + let postscript = format!("{}-Regular", family.replace(' ', "")); + (named_copy(false, (family, "Regular", "Version 1.000", &postscript)).unwrap(), postscript) + }; + let mut s = session(); + let g = outlined(&mut s, json!({"x": 40, "y": 100, "text": "Rg", "size": 40, "font": "Source Sans 3", "style": "Regular"})); + s.execute("select.set", &json!({"ids": [g]})).unwrap(); + // Loaded copies that match fill most of the list. + let loaded = FontDb::with_font_dirs(vec![]); + for i in 0..super::MAX_COUNT { + loaded.add_font(copy(&format!("Fullcopy {i:02}")).0); + } + let listed = names(&query(&mut s, json!({"count": 96, "installed": false}), &loaded)).len(); + assert!(listed < super::MAX_COUNT, "{listed}"); + // Installed copies, two more than the places left. + let dir = vectorcraft_testkit::temp_dir("retype-fonts-installed-full"); + for i in 0..super::MAX_COUNT - listed + 2 { + let (data, postscript) = copy(&format!("Installed {i:02}")); + std::fs::write(dir.join(format!("{postscript}.ttf")), data).unwrap(); + } + let db = FontDb::with_font_dirs(vec![dir]); + for i in 0..super::MAX_COUNT { + db.add_font(copy(&format!("Fullcopy {i:02}")).0); + } + let r = query(&mut s, json!({"count": 96}), &db); + assert_eq!(names(&r).len(), super::MAX_COUNT, "the installed copies fill the places left: {r}"); + assert_eq!(r["more"], json!(false), "no font past the list is found: {r}"); + assert_eq!(r["installed"]["skipped"], json!(2), "{r}"); + assert_eq!(db.unloaded_installed_faces().len(), 2, "the two past the list stay unloaded"); +} + #[test] fn shapes_that_stay_outlines_still_name_their_font() { // A glyph with paint type cannot take (two fills) is not retyped, but it is still that font's glyph. diff --git a/crates/engine/src/cmd/retype_installed.rs b/crates/engine/src/cmd/retype_installed.rs new file mode 100644 index 0000000000..6a40ba5791 --- /dev/null +++ b/crates/engine/src/cmd/retype_installed.rs @@ -0,0 +1,363 @@ +//! Retype's installed fonts: the faces of installed fonts that nothing has loaded yet are +//! candidates too, as the fonts on the device are among the sources Retype suggests fonts from +//! (). +//! Each font file is read for the search and let go; a face whose glyphs match a shape is loaded +//! as it was read, without the family's other files. Files are read smallest first, within a budget +//! of bytes read and glyphs drawn, and the search stops between files when it is canceled. The app +//! runs it off the UI thread ([`RetypeRun`]), with a Cancel. + +use std::collections::BTreeSet; +use std::sync::Arc; + +use kurbo::BezPath; +use serde_json::{Value, json}; +use vectorcraft_doc::{Document, NodeId}; +use vectorcraft_text::retype::{MAX_FACES, RetypeIndex, encoded_glyphs, is_plain, shape_key}; +use vectorcraft_text::{FontDb, FontFace}; + +use super::super::{EngineError, Result, Session, bad}; + +/// How much one search reads. +#[derive(Clone, Copy)] +struct Limits { + /// Font files (a suitcase font's resource fork) longer than this are not read. + file: u64, + /// The bytes of font files read, in all. + read: u64, + /// The glyphs of installed faces drawn, in all, to tell which can match a shape. + glyphs: usize, + /// The faces found: the faces after the last one found are not compared. + faces: usize, +} + +const LIMITS: Limits = Limits { file: 256 << 20, read: 2 << 30, glyphs: 500_000, faces: MAX_FACES }; + +/// The `installed` param: whether to look in the installed fonts (default true). +pub(super) fn wanted(cmd: &str, p: &Value) -> Result { + match p.get("installed") { + None | Some(Value::Null) => Ok(true), + Some(Value::Bool(b)) => Ok(*b), + Some(_) => Err(bad(cmd, "`installed` must be true, false or null")), + } +} + +/// What a search of the installed fonts found and read. +#[derive(Default)] +pub(super) struct Installed { + /// The faces whose glyphs match a shape, loaded now, in the order they were read. + pub(super) faces: Vec>, + /// Faces read and compared. + pub(super) read: usize, + /// Faces left out by the limits ([`LIMITS`]). + pub(super) skipped: usize, +} + +impl Installed { + /// As a command's result reports it. + pub(super) fn json(&self) -> Value { + json!({"read": self.read, "skipped": self.skipped}) + } +} + +/// The installed faces nothing has loaded whose glyphs match at least one of `shapes` that is not +/// plain ([`is_plain`]: a rectangle, a triangle or a bar), each loaded into `db` as it was read. +/// With `every` false the search stops once each such shape matches a face found; with it, every +/// face within the limits ([`LIMITS`]) is compared. No file is read when every shape is plain. At +/// most [`MAX_FACES`] faces are found; the faces not compared past that count as skipped. +pub(super) fn search(db: &FontDb, shapes: &[&BezPath], every: bool) -> Result { + search_within(db, shapes, every, LIMITS, &|_| true) +} + +/// [`search`] comparing every face within the limits, for a list of at most `faces` faces: a face +/// found that `listed` turns down is loaded and not listed, and takes no place of the `faces`. +pub(super) fn search_listed(db: &FontDb, shapes: &[&BezPath], faces: usize, listed: &dyn Fn(&FontFace) -> bool) -> Result { + search_within(db, shapes, true, Limits { faces: faces.min(MAX_FACES), ..LIMITS }, listed) +} + +/// An installed font file: its path, its length and the (family, style) of the faces wanted from it. +type File = (std::path::PathBuf, u64, Vec<(String, String)>); + +/// [`search`] within `limits`, keeping in its faces only those `listed` accepts. +fn search_within(db: &FontDb, shapes: &[&BezPath], every: bool, limits: Limits, listed: &dyn Fn(&FontFace) -> bool) -> Result { + let mut out = Installed::default(); + let shapes: Vec<&BezPath> = shapes.iter().copied().filter(|s| !is_plain(s)).collect(); + let keys: BTreeSet = shapes.iter().filter_map(|s| shape_key(s)).collect(); + if keys.is_empty() { + return Ok(out); + } + let keys = &keys; + // The faces wanted from each file, smallest file first. + let mut files: Vec = vec![]; + let mut at: std::collections::HashMap = std::collections::HashMap::new(); + for f in db.unloaded_installed_faces() { + match at.get(&f.path).and_then(|i| files.get_mut(*i)) { + Some(file) => file.2.push((f.family, f.style)), + None => { + at.insert(f.path.clone(), files.len()); + files.push((f.path, f.len, vec![(f.family, f.style)])); + } + } + } + files.sort_by(|a, b| a.1.cmp(&b.1).then_with(|| a.0.cmp(&b.0))); + let mut matched = vec![false; shapes.len()]; + let (mut bytes_left, mut glyphs_left) = (limits.read, limits.glyphs); + let total = files.len() as u64; + for (i, (path, len, styles)) in files.iter().enumerate() { + vectorcraft_doc::cancel::check()?; + vectorcraft_doc::cancel::progress(i as u64, total, "Retype: reading installed fonts"); + if *len > limits.file || *len > bytes_left { + out.skipped += styles.len(); + continue; + } + // A file that grew since the scan is read only within what is left. + let faces = db.read_unloaded_file(path, limits.file.min(bytes_left)); + // The bytes read: the file's fonts (a collection's faces share one), or its length then. + let mut datas: Vec<(usize, usize)> = faces.iter().map(|f| (f.file_data().as_ptr() as usize, f.file_data().len())).collect(); + datas.sort_unstable(); + datas.dedup(); + let read = datas.iter().map(|d| d.1 as u64).sum::().max(*len); + bytes_left = bytes_left.saturating_sub(read); + let wanted = |f: &FontFace| styles.iter().any(|(family, style)| f.family.eq_ignore_ascii_case(family) && f.style.eq_ignore_ascii_case(style)); + let faces: Vec> = faces.into_iter().filter(|f| wanted(f)).collect(); + for (j, face) in faces.iter().enumerate() { + if out.faces.len() >= limits.faces { + // The faces not compared past the cap: the rest of this file's and the later files'. + out.skipped += faces.len() - j + files.iter().skip(i + 1).map(|f| f.2.len()).sum::(); + return Ok(out); + } + let n = encoded_glyphs(face); + if n > glyphs_left { + out.skipped += 1; + continue; + } + glyphs_left -= n; + out.read += 1; + let index = RetypeIndex::build_unloaded(db, face.clone(), keys); + if index.is_empty() { + continue; + } + let fits: Vec = shapes + .iter() + .zip(&matched) + .enumerate() + .filter(|(_, (s, m))| (every || !**m) && !index.matches(s).is_empty()) + .map(|(k, _)| k) + .collect(); + if fits.is_empty() { + continue; + } + let loaded = load(db, face); + let fits = still_fit(db, face, &loaded, &shapes, keys, fits); + if fits.is_empty() { + continue; + } + remember(db, &loaded); + if listed(&loaded) && !out.faces.iter().any(|f| f.id() == loaded.id()) { + out.faces.push(loaded); + } + for k in fits { + if let Some(m) = matched.get_mut(k) { + *m = true; + } + } + if !every && matched.iter().all(|m| *m) { + return Ok(out); + } + } + // The cap reached with the file's last face: the later files are not compared. + if out.faces.len() >= limits.faces { + out.skipped += files.iter().skip(i + 1).map(|f| f.2.len()).sum::(); + return Ok(out); + } + } + Ok(out) +} + +/// The faces searches loaded from installed files, by database ([`FontDb::id`]) and face id, the +/// latest first: at most [`MAX_FACES`]. +static FOUND: std::sync::Mutex> = std::sync::Mutex::new(Vec::new()); + +/// Keep `face`, which a search loaded into `db`, among [`found`]'s faces. +fn remember(db: &FontDb, face: &FontFace) { + let mut kept = FOUND.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + let at = (db.id(), face.id()); + kept.retain(|k| *k != at); + kept.insert(0, at); + kept.truncate(MAX_FACES); +} + +/// The faces of `db` that searches of the installed fonts found and loaded, the latest first. A +/// later Retype compares them ahead of the other loaded faces. +pub(super) fn found(db: &FontDb) -> Vec> { + let kept = FOUND.lock().unwrap_or_else(std::sync::PoisonError::into_inner).clone(); + kept.into_iter().filter(|(d, _)| *d == db.id()).filter_map(|(_, id)| db.face_by_id(id)).collect() +} + +/// Of `fits` (indices into `shapes` that `read` matches), those that `loaded`, the face loading +/// `read` gave, matches too: all of them when it is `read` itself. Another face of the same +/// family, style and version, loaded from another file, may have other glyphs. +fn still_fit(db: &FontDb, read: &FontFace, loaded: &Arc, shapes: &[&BezPath], keys: &BTreeSet, fits: Vec) -> Vec { + if loaded.id() == read.id() { + return fits; + } + let index = RetypeIndex::build(db, [loaded.clone()], keys); + fits.into_iter().filter(|k| shapes.get(*k).is_some_and(|s| !index.matches(s).is_empty())).collect() +} + +/// `face` (read from an installed file and not loaded) loaded into `db` as it was read +/// ([`FontDb::load_read_face`]): neither its file nor the family's other files are read again. +fn load(db: &FontDb, face: &Arc) -> Arc { + db.load_read_face(face.clone()) +} + +/// A search of the installed fonts made away from its command, so the app can run it off the UI +/// thread with a Cancel. [`RetypeRun::prepare`] takes the selected shapes and the loaded faces to +/// compare from the session, checking the params as the command checks them; [`RetypeSearch::run`] +/// compares them and searches the installed fonts on any thread, loading the faces that match; and +/// [`RetypeFound::hand_in`] gives what it found to the command, which then runs with +/// [`RetypeRun::params`] and compares those faces as its own search would, without reading the +/// installed fonts again. +pub struct RetypeRun { + params: Value, + /// The document ([`crate::DocState::uid`]), its content and the selection the search is for. + doc: u64, + content: Arc, + selection: Vec, + search: Arc, +} + +/// What a [`RetypeRun`] compares and searches, without the session: it can be sent to another +/// thread ([`RetypeRun::search`]). +pub struct RetypeSearch { + command: &'static str, + /// The document it is for ([`crate::DocState::uid`]). + doc: u64, + /// The shapes to match, and the loaded faces they are compared with first. + shapes: Vec, + faces: Vec>, +} + +/// What a [`RetypeSearch`] found in the installed fonts: the faces whose glyphs match, loaded, and +/// what it read. +pub struct RetypeFound { + doc: u64, + installed: Installed, +} + +impl RetypeFound { + /// Hand it to the next `type.retype` or `type.retypeFonts`, which compares the faces found as + /// its own search of the installed fonts would, in the document the search was made for. Any + /// such command takes it; one in another document compares only what is loaded. + pub fn hand_in(self, s: &mut Session) { + s.retype_hand_off = Some(self); + } + + /// What it read, as the commands report it. + pub fn json(&self) -> Value { + self.installed.json() + } +} + +/// What a search found for the active document of `s`, handed in for this command ([`RetypeFound`]). +/// It is taken whatever the document, so it is used once. +pub(super) fn handed(s: &mut Session) -> Option { + let found = s.retype_hand_off.take()?; + let doc = s.doc().ok()?.uid; + (found.doc == doc).then_some(found.installed) +} + +impl RetypeRun { + /// The search `command` (`type.retype` or `type.retypeFonts`) with params `p` makes in the + /// active document. None when it reads no installed font: `installed` is false, or no shape has + /// a glyph's key. An error where the command fails on its params or on the selection. + pub fn prepare(s: &Session, command: &str, p: &Value) -> Result> { + Self::prepare_in(s, command, p, FontDb::global()) + } + + /// [`RetypeRun::prepare`] with the fonts of `db`. + fn prepare_in(s: &Session, command: &str, p: &Value, db: &FontDb) -> Result> { + let (command, fonts) = match command { + "type.retype" => ("type.retype", Some(super::fonts_param(p)?)), + "type.retypeFonts" => { + super::fonts::count_param(p)?; + ("type.retypeFonts", None) + } + other => return Err(EngineError::Other(format!("`{other}` doesn't search the installed fonts"))), + }; + if !wanted(command, p)? { + return Ok(None); + } + let (pieces, _) = super::selected_pieces(s)?; + let st = s.doc()?; + // Retype compares the shapes that may become type; the list compares every shape. + let shapes: Vec = pieces.into_iter().filter(|pc| fonts.is_none() || !pc.keeps_outline).map(|pc| pc.path).collect(); + if !shapes.iter().any(|sh| shape_key(sh).is_some()) { + return Ok(None); + } + let faces = match &fonts { + Some(fonts) => super::candidate_faces(db, &st.doc, fonts), + None => super::fonts::listed_faces(db, &st.doc), + }; + Ok(Some(RetypeRun { + params: p.clone(), + doc: st.uid, + content: st.doc.clone(), + selection: st.selection.objects.clone(), + search: Arc::new(RetypeSearch { command, doc: st.uid, shapes, faces }), + })) + } + + /// `type.retype` or `type.retypeFonts`. + pub fn command(&self) -> &'static str { + self.search.command + } + + /// What it compares and searches, for another thread. + pub fn search(&self) -> Arc { + self.search.clone() + } + + /// The command's params: those it was prepared with. + pub fn params(&self) -> &Value { + &self.params + } + + /// Does it still apply: is the document it was prepared in active, with the same content and + /// the same objects selected? + pub fn current(&self, s: &Session) -> bool { + s.doc().is_ok_and(|st| st.uid == self.doc && Arc::ptr_eq(&st.doc, &self.content) && st.selection.objects == self.selection) + } + + /// [`RetypeSearch::run`] with the fonts of `db`. + #[cfg(test)] + fn run_in(&self, db: &FontDb) -> Result { + self.search.run_in(db) + } +} + +impl RetypeSearch { + /// Compare the shapes with the loaded faces, then search the installed fonts as the command + /// would, loading the faces that match → what it found ([`EngineError::Cancelled`] when a + /// cancel stopped it). It touches no document, so it can run on any thread. + pub fn run(&self) -> Result { + self.run_in(FontDb::global()) + } + + /// [`RetypeSearch::run`] with the fonts of `db`. + fn run_in(&self, db: &FontDb) -> Result { + let shapes: Vec<&BezPath> = self.shapes.iter().collect(); + let installed = if self.command == "type.retypeFonts" { + super::fonts::rank_fonts(db, self.faces.clone(), &shapes, true, None)?.1 + } else { + let keys: BTreeSet = shapes.iter().filter_map(|sh| shape_key(sh)).collect(); + let index = RetypeIndex::build(db, self.faces.iter().cloned(), &keys); + let left: Vec<&BezPath> = shapes.iter().copied().filter(|sh| index.matches(sh).is_empty()).collect(); + search(db, &left, false)? + }; + Ok(RetypeFound { doc: self.doc, installed }) + } +} + +#[cfg(test)] +#[path = "retype_installed_tests.rs"] +mod tests; diff --git a/crates/engine/src/cmd/retype_installed_tests.rs b/crates/engine/src/cmd/retype_installed_tests.rs new file mode 100644 index 0000000000..633028a42c --- /dev/null +++ b/crates/engine/src/cmd/retype_installed_tests.rs @@ -0,0 +1,359 @@ +use std::collections::BTreeSet; +use std::path::PathBuf; + +use kurbo::{Affine, BezPath, Shape}; +use serde_json::json; +use vectorcraft_text::FontDb; +use vectorcraft_text::retype::shape_key; + +use super::{Limits, search, search_within}; +use crate::Session; + +/// A database whose installed fonts are copies of the bundled Source Sans 3 Regular named +/// `families`, one file each, in a folder of their own: they are installed and not loaded. +/// Returns the database and the files. +fn installed(tag: &str, families: &[&str]) -> (FontDb, Vec) { + let dir = vectorcraft_testkit::temp_dir(&format!("retype-installed-{tag}")); + let mut files = vec![]; + for family in families { + let postscript = format!("{}-Regular", family.replace(' ', "")); + let data = vectorcraft_text::test_fonts::named_copy(false, (family, "Regular", "Version 1.000", &postscript)).unwrap(); + let path = dir.join(format!("{postscript}.ttf")); + std::fs::write(&path, data).unwrap(); + files.push(path); + } + (FontDb::with_font_dirs(vec![dir]), files) +} + +/// The glyphs of `text` in the bundled Source Sans 3 Regular, as outlines at 30 pt. +fn glyphs(db: &FontDb, text: &str) -> Vec { + let face = db.face("Source Sans 3", "Regular").unwrap(); + text.chars() + .enumerate() + .map(|(i, c)| Affine::translate((40.0 + 30.0 * i as f64, 100.0)) * Affine::scale(0.03) * db.outline_uncached(&face, face.glyph_for(c))) + .collect() +} + +fn keys(shapes: &[BezPath]) -> BTreeSet { + shapes.iter().filter_map(shape_key).collect() +} + +fn unloaded(db: &FontDb, family: &str) -> bool { + db.unloaded_installed_faces().iter().any(|f| f.family == family) +} + +#[test] +fn an_installed_face_whose_glyphs_match_is_found_and_loaded() { + let (db, files) = installed("found", &["Retype Copy A"]); + assert!(unloaded(&db, "Retype Copy A")); + let shapes = glyphs(&db, "Rx"); + let refs: Vec<&BezPath> = shapes.iter().collect(); + let found = search(&db, &refs, false).unwrap(); + assert_eq!((found.read, found.skipped), (1, 0)); + let face = found.faces.first().expect("the installed copy matches"); + assert_eq!((face.family.as_str(), face.style.as_str()), ("Retype Copy A", "Regular")); + assert_eq!(face.path(), Some(files[0].as_path())); + // Loaded now, as it was read. + assert!(db.loaded_faces().iter().any(|f| f.id() == face.id())); + assert!(!unloaded(&db, "Retype Copy A")); + assert_eq!(found.json(), json!({"read": 1, "skipped": 0})); + // A later Retype compares it ahead of the other loaded faces, however many are loaded. + assert_eq!(super::found(&db).first().map(|f| f.id()), Some(face.id())); + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 600, "height": 400})).unwrap(); + let candidates = super::super::candidate_faces(&db, &s.doc().unwrap().doc, &[]); + assert_eq!(candidates.first().map(|f| f.id()), Some(face.id())); + // Only this database's faces. + assert!(super::found(&FontDb::with_font_dirs(vec![])).is_empty()); +} + +#[test] +fn a_matching_face_loads_without_the_family_s_other_files() { + let dir = vectorcraft_testkit::temp_dir("retype-installed-family"); + for style in ["Regular", "Bold"] { + let data = + vectorcraft_text::test_fonts::named_copy(false, ("Retype Copy N", style, "Version 1.000", &format!("RetypeCopyN-{style}"))).unwrap(); + std::fs::write(dir.join(format!("RetypeCopyN-{style}.ttf")), data).unwrap(); + } + let db = FontDb::with_font_dirs(vec![dir]); + let shapes = glyphs(&db, "Rx"); + let refs: Vec<&BezPath> = shapes.iter().collect(); + let found = search(&db, &refs, false).unwrap(); + assert_eq!((found.read, found.faces.len()), (1, 1)); + let style = found.faces[0].style.clone(); + let loaded: Vec = db.loaded_faces().iter().filter(|f| f.family == "Retype Copy N").map(|f| f.style.clone()).collect(); + assert_eq!(loaded, std::slice::from_ref(&style), "only the face that matched is loaded"); + let left: Vec = db.unloaded_installed_faces().into_iter().filter(|f| f.family == "Retype Copy N").map(|f| f.style).collect(); + assert_eq!(left.len(), 1); + assert_ne!(left[0], style); +} + +#[test] +fn a_loaded_face_of_the_same_names_counts_only_for_the_shapes_it_matches() { + use vectorcraft_text::test_fonts::named_copy; + let names = ("Retype Twin", "Regular", "Version 1.000", "RetypeTwin-Regular"); + let db = FontDb::with_font_dirs(vec![]); + // Inter's glyphs, loaded under the names a file of Source Sans 3's glyphs has too. + db.add_font(named_copy(true, names).unwrap()); + let dir = vectorcraft_testkit::temp_dir("retype-installed-twin"); + let path = dir.join("RetypeTwin-Regular.ttf"); + std::fs::write(&path, named_copy(false, names).unwrap()).unwrap(); + let read = db.read_unloaded_file(&path, u64::MAX).into_iter().next().unwrap(); + let shapes = glyphs(&db, "Rx"); + let refs: Vec<&BezPath> = shapes.iter().collect(); + let keys = keys(&shapes); + let loaded = super::load(&db, &read); + assert_ne!(loaded.id(), read.id(), "the face loaded first is kept"); + assert!(super::still_fit(&db, &read, &loaded, &refs, &keys, vec![0, 1]).is_empty(), "Inter's R and x are not these"); + assert_eq!(super::still_fit(&db, &read, &read, &refs, &keys, vec![0, 1]), [0, 1]); +} + +#[test] +fn an_installed_face_no_shape_matches_is_read_and_not_loaded() { + let (db, _) = installed("none", &["Retype Copy B"]); + let shapes = [kurbo::Circle::new((40.0, 40.0), 20.0).to_path(0.1)]; + let refs: Vec<&BezPath> = shapes.iter().collect(); + let found = search(&db, &refs, false).unwrap(); + assert_eq!((found.read, found.faces.len()), (1, 0)); + assert!(unloaded(&db, "Retype Copy B"), "a face that matches nothing stays unloaded"); + // No shape: no file is read. + let none = search(&db, &[], false).unwrap(); + assert_eq!((none.read, none.skipped), (0, 0)); +} + +#[test] +fn plain_shapes_alone_read_no_installed_font() { + // A hyphen is a bar: many fonts have a glyph of its shape, so it tells no font apart. + let (db, _) = installed("plain", &["Retype Copy L"]); + let mut shapes = glyphs(&db, "-"); + shapes.push(kurbo::Rect::new(0.0, 0.0, 80.0, 40.0).to_path(0.1)); + assert!(shapes.iter().all(vectorcraft_text::retype::is_plain)); + let refs: Vec<&BezPath> = shapes.iter().collect(); + for every in [false, true] { + let found = search(&db, &refs, every).unwrap(); + assert_eq!((found.read, found.skipped, found.faces.len()), (0, 0, 0)); + } + assert!(unloaded(&db, "Retype Copy L")); + // Beside a shape that is not plain, the search reads the file for that shape. + shapes.extend(glyphs(&db, "q")); + let refs: Vec<&BezPath> = shapes.iter().collect(); + assert_eq!(search(&db, &refs, false).unwrap().faces.len(), 1); +} + +#[test] +fn the_search_stops_once_every_shape_matches_unless_every_face_is_wanted() { + let (db, _) = installed("every", &["Retype Copy C", "Retype Copy D"]); + let shapes = glyphs(&db, "ab"); + let refs: Vec<&BezPath> = shapes.iter().collect(); + let first = search(&db, &refs, false).unwrap(); + assert_eq!((first.read, first.faces.len()), (1, 1), "the second file is not read"); + let (db, _) = installed("every-all", &["Retype Copy E", "Retype Copy F"]); + let all = search(&db, &refs, true).unwrap(); + assert_eq!((all.read, all.faces.len()), (2, 2)); + let mut families: Vec<&str> = all.faces.iter().map(|f| f.family.as_str()).collect(); + families.sort_unstable(); + assert_eq!(families, ["Retype Copy E", "Retype Copy F"]); +} + +#[test] +fn faces_past_the_limits_are_skipped_and_counted() { + let (db, files) = installed("limits", &["Retype Copy G", "Retype Copy H"]); + let shapes = glyphs(&db, "k"); + let refs: Vec<&BezPath> = shapes.iter().collect(); + let len = files.iter().map(|f| std::fs::metadata(f).unwrap().len()).max().unwrap(); + // Files longer than the limit for one file. + let open = Limits { file: u64::MAX, read: u64::MAX, glyphs: usize::MAX, faces: usize::MAX }; + let all = |_: &vectorcraft_text::FontFace| true; + let small = search_within(&db, &refs, true, Limits { file: len / 2, ..open }, &all).unwrap(); + assert_eq!((small.read, small.skipped, small.faces.len()), (0, 2, 0)); + // Bytes for one file only. + let one = search_within(&db, &refs, true, Limits { read: len + len / 2, ..open }, &all).unwrap(); + assert_eq!((one.read, one.skipped, one.faces.len()), (1, 1, 1)); + // Glyphs for no face. + let (db, _) = installed("limits-glyphs", &["Retype Copy I"]); + let few = search_within(&db, &refs, true, Limits { glyphs: 10, ..open }, &all).unwrap(); + assert_eq!((few.read, few.skipped, few.faces.len()), (0, 1, 0)); + assert!(unloaded(&db, "Retype Copy I")); + // Faces found up to the cap: the faces after it are not compared, and count as skipped. + let (db, _) = installed("limits-faces", &["Retype Copy O", "Retype Copy P", "Retype Copy Q"]); + let capped = search_within(&db, &refs, true, Limits { faces: 1, ..open }, &all).unwrap(); + assert_eq!((capped.read, capped.skipped, capped.faces.len()), (1, 2, 1)); +} + +#[test] +fn faces_a_list_turns_down_are_loaded_and_take_no_place() { + let (db, _) = installed("listed", &["Retype Copy R", "Retype Copy S", "Retype Copy T"]); + let shapes = glyphs(&db, "k"); + let refs: Vec<&BezPath> = shapes.iter().collect(); + // Two places, and the first face found is turned down: the next two are listed. + let found = super::search_listed(&db, &refs, 2, &|f| f.family != "Retype Copy R").unwrap(); + let mut families: Vec<&str> = found.faces.iter().map(|f| f.family.as_str()).collect(); + families.sort_unstable(); + assert_eq!(families, ["Retype Copy S", "Retype Copy T"]); + assert_eq!((found.read, found.skipped), (3, 0)); + assert!(!unloaded(&db, "Retype Copy R"), "the face turned down was loaded"); +} + +#[test] +fn a_cancel_stops_the_search_between_files() { + let (db, _) = installed("cancel-between", &["Retype Copy U", "Retype Copy V", "Retype Copy W"]); + let shapes = glyphs(&db, "k"); + let refs: Vec<&BezPath> = shapes.iter().collect(); + let token = vectorcraft_doc::cancel::CancelToken::new(); + let stop = token.clone(); + // The cancel comes as the second file starts: it is read, the third is not. + let sink: vectorcraft_doc::cancel::ProgressSink = std::rc::Rc::new(move |done, _, _| { + if done == 1 { + stop.cancel(); + } + }); + let r = vectorcraft_doc::cancel::scope(&token, Some(sink), || search(&db, &refs, true)); + assert!(matches!(r, Err(crate::EngineError::Cancelled))); + let left = ["Retype Copy U", "Retype Copy V", "Retype Copy W"].iter().filter(|f| unloaded(&db, f)).count(); + assert_eq!(left, 1, "two files were read and loaded, the third was not"); +} + +#[test] +fn a_run_away_from_the_command_loads_the_faces_it_finds() { + let (db, _) = installed("run", &["Retype Copy X"]); + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 600, "height": 400})).unwrap(); + let ids: Vec = + glyphs(&db, "Wk").iter().map(|p| s.execute("path.create", &json!({"d": p.to_svg()})).unwrap()["id"].as_u64().unwrap()).collect(); + s.execute("select.set", &json!({"ids": ids})).unwrap(); + // Off: nothing to run. + for cmd in ["type.retype", "type.retypeFonts"] { + assert!(super::RetypeRun::prepare_in(&s, cmd, &json!({"installed": false}), &db).unwrap().is_none()); + } + // The command's params are checked as it checks them. + assert!(super::RetypeRun::prepare_in(&s, "type.retypeFonts", &json!({"count": 0}), &db).is_err()); + assert!(super::RetypeRun::prepare_in(&s, "type.retype", &json!({"fonts": 1}), &db).is_err()); + assert!(super::RetypeRun::prepare_in(&s, "type.text", &json!({}), &db).is_err()); + // Retype: the loaded Source Sans 3 matches both shapes, so no installed file is read. + let run = super::RetypeRun::prepare_in(&s, "type.retype", &json!({}), &db).unwrap().unwrap(); + assert_eq!(run.command(), "type.retype"); + assert_eq!(run.params(), &json!({})); + assert_eq!(run.run_in(&db).unwrap().json(), json!({"read": 0, "skipped": 0})); + assert!(unloaded(&db, "Retype Copy X")); + // The list compares every installed face: the copy is read and loaded. + let run = super::RetypeRun::prepare_in(&s, "type.retypeFonts", &json!({"count": 5}), &db).unwrap().unwrap(); + assert_eq!(run.params(), &json!({"count": 5})); + assert!(run.current(&s)); + let found = run.run_in(&db).unwrap(); + assert_eq!(found.json(), json!({"read": 1, "skipped": 0})); + assert_eq!(found.installed.faces.iter().map(|f| f.family.as_str()).collect::>(), ["Retype Copy X"]); + assert!(!unloaded(&db, "Retype Copy X")); + // A change of selection or content: it no longer applies. + s.execute("select.set", &json!({"ids": [ids[0]]})).unwrap(); + assert!(!run.current(&s)); + s.execute("select.set", &json!({"ids": ids})).unwrap(); + assert!(run.current(&s)); + s.execute("object.move", &json!({"dx": 1, "dy": 0})).unwrap(); + assert!(!run.current(&s)); +} + +#[test] +fn what_a_search_found_is_handed_to_the_next_command_in_its_document() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 600, "height": 400})).unwrap(); + let id = s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 20, "height": 20})).unwrap()["id"].as_u64().unwrap(); + s.execute("select.set", &json!({"ids": [id]})).unwrap(); + let uid = s.doc().unwrap().uid; + let handed = |doc| super::RetypeFound { doc, installed: super::Installed { read: 7, skipped: 3, ..Default::default() } }; + // Taken instead of a search of the installed fonts, also with installed false. + handed(uid).hand_in(&mut s); + let r = s.execute("type.retypeFonts", &json!({"installed": false})).unwrap(); + assert_eq!(r["installed"], json!({"read": 7, "skipped": 3}), "{r}"); + // Used once. + let r = s.execute("type.retypeFonts", &json!({"installed": false})).unwrap(); + assert_eq!(r["installed"], json!({"read": 0, "skipped": 0}), "{r}"); + // Another document's is dropped. + handed(uid + 1).hand_in(&mut s); + let r = s.execute("type.retypeFonts", &json!({"installed": false})).unwrap(); + assert_eq!(r["installed"], json!({"read": 0, "skipped": 0}), "{r}"); + assert!(s.retype_hand_off.is_none(), "taken"); + // Retype takes it too, whether or not a loaded font matches the rectangle. + handed(uid).hand_in(&mut s); + let _ = s.execute("type.retype", &json!({"installed": false})); + assert!(s.retype_hand_off.is_none()); +} + +#[test] +fn a_canceled_search_stops_before_reading_a_file() { + let (db, _) = installed("cancel", &["Retype Copy J"]); + let shapes = glyphs(&db, "z"); + let refs: Vec<&BezPath> = shapes.iter().collect(); + let token = vectorcraft_doc::cancel::CancelToken::new(); + token.cancel(); + let r = vectorcraft_doc::cancel::scope(&token, None, || search(&db, &refs, false)); + assert!(matches!(r, Err(crate::EngineError::Cancelled))); + assert!(unloaded(&db, "Retype Copy J"), "nothing was loaded"); +} + +/// The shapes of `text` set in Source Sans 3 and outlined, as `type.retype` collects them. +fn pieces(text: &str) -> Vec { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 600, "height": 400})).unwrap(); + let id = + s.execute("text.create", &json!({"x": 40, "y": 100, "text": text, "size": 30, "font": "Source Sans 3"})).unwrap()["id"].as_u64().unwrap(); + s.execute("select.set", &json!({"ids": [id]})).unwrap(); + let group = s.execute("type.createOutlines", &json!({})).unwrap()["ids"][0].as_u64().unwrap(); + let d = &s.doc().unwrap().doc; + let node = d.node(vectorcraft_doc::NodeId(group)).unwrap(); + let (mut barrier, mut truncated, mut pieces) = (true, false, vec![]); + super::super::collect(node, None, 0, &mut barrier, &mut truncated, &mut pieces); + pieces +} + +#[test] +fn retype_fills_the_shapes_no_loaded_font_matches_from_the_installed_fonts() { + let (db, _) = installed("retype", &["Retype Copy K"]); + let pieces = pieces("Wk-"); + assert_eq!(pieces.len(), 3); + // The first shape is taken as matched already: the others are looked for. + let mut found = vec![vec![], vec![], vec![]]; + let keep = super::super::RetypeIndex::build(&db, db.face("Source Sans 3", "Regular"), &keys(&[pieces[0].path.clone()])); + found[0] = keep.matches(&pieces[0].path); + assert!(!found[0].is_empty()); + let installed = super::super::from_installed(&db, &pieces, &mut found).unwrap(); + assert_eq!(installed.read, 1); + assert_eq!(found[0].first().map(|m| m.face.family.as_str()), Some("Source Sans 3"), "a matched shape keeps its match"); + // and gets the face found too, so its line can be set in the face the others match. + assert!(found[0].iter().any(|m| m.face.family == "Retype Copy K" && m.ch == 'W'), "the W also matches the face found"); + let m = found[1].first().expect("the installed copy matches the k"); + assert_eq!((m.face.family.as_str(), m.ch), ("Retype Copy K", 'k')); + assert!(db.loaded_faces().iter().any(|f| f.id() == m.face.id()), "the match is in a loaded face"); + // The hyphen, a plain shape, matches the font the k found. + let m = found[2].first().expect("the installed copy matches the hyphen"); + assert_eq!((m.face.family.as_str(), m.ch), ("Retype Copy K", '-')); +} + +#[test] +fn retype_reads_no_installed_font_for_plain_shapes_alone() { + let (db, _) = installed("retype-plain", &["Retype Copy M"]); + let pieces = pieces("W-"); + let mut found = vec![vec![], vec![]]; + let keep = super::super::RetypeIndex::build(&db, db.face("Source Sans 3", "Regular"), &keys(&[pieces[0].path.clone()])); + found[0] = keep.matches(&pieces[0].path); + let installed = super::super::from_installed(&db, &pieces, &mut found).unwrap(); + assert_eq!((installed.read, installed.faces.len()), (0, 0)); + assert!(found[1].is_empty(), "the hyphen alone stays unmatched"); + assert!(unloaded(&db, "Retype Copy M")); +} + +#[test] +fn installed_must_be_a_bool_or_null() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 600, "height": 400})).unwrap(); + let id = s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 20, "height": 20})).unwrap()["id"].as_u64().unwrap(); + s.execute("select.set", &json!({"ids": [id]})).unwrap(); + for cmd in ["type.retype", "type.retypeFonts"] { + for bad in [json!(1), json!("yes"), json!([])] { + let e = s.execute(cmd, &json!({"installed": bad})).unwrap_err().to_string(); + assert!(e.contains("`installed` must be true, false or null"), "{cmd} {bad}: {e}"); + } + } + // false: no installed font is read, and the result says so. + let r = s.execute("type.retypeFonts", &json!({"installed": false})).unwrap(); + assert_eq!(r["installed"], json!({"read": 0, "skipped": 0}), "{r}"); +} diff --git a/crates/engine/src/cmd/retype_tests.rs b/crates/engine/src/cmd/retype_tests.rs index 80361f1e0a..781865d7bf 100644 --- a/crates/engine/src/cmd/retype_tests.rs +++ b/crates/engine/src/cmd/retype_tests.rs @@ -209,7 +209,7 @@ fn an_open_path_along_a_glyph_is_not_a_glyph() { }) .unwrap(); s.execute("select.set", &json!({"ids": [g]})).unwrap(); - assert!(s.execute("type.retype", &json!({})).is_err(), "nothing matches"); + assert!(s.execute("type.retype", &json!({"installed": false})).is_err(), "nothing matches"); } #[test] @@ -386,7 +386,8 @@ fn a_drawn_dot_or_bar_beside_type_stays_art() { // A bar that is exactly a hyphen of the font, somewhere else: the worst case. let bar = outlined(&mut s, json!({"x": 200, "y": 300, "text": "-", "size": 50})); s.execute("select.set", &json!({"ids": [g, dot, bar]})).unwrap(); - let r = s.execute("type.retype", &json!({})).unwrap(); + // The installed fonts left out: what this machine has installed does not change the result. + let r = s.execute("type.retype", &json!({"installed": false})).unwrap(); assert_eq!(r["texts"], json!(["AB"]), "{r}"); let un = r["unmatched"].as_array().unwrap(); assert!(un.contains(&json!(dot)) && un.len() == 2, "the dot and the bar stay art: {r}"); @@ -548,8 +549,9 @@ fn two_overlapping_lone_glyphs_beside_art_stay_outlines() { let b = outlined(&mut s, json!({"x": 49, "y": 100, "text": "M", "size": 30})); let dot = s.execute("shape.ellipse", &json!({"x": 300, "y": 60, "width": 8, "height": 8})).unwrap()["id"].as_u64().unwrap(); s.execute("select.set", &json!({"ids": [a, b, dot]})).unwrap(); - // Nothing is left to retype: both stay outlines, as the lone bar beside art does. - let e = s.execute("type.retype", &json!({})).unwrap_err(); + // Nothing is left to retype: both stay outlines, as the lone bar beside art does. The installed + // fonts are left out, so what this machine has installed does not change the result. + let e = s.execute("type.retype", &json!({"installed": false})).unwrap_err(); assert!(format!("{e:?}").contains("no selected shape matches"), "{e:?}"); } diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index e2e6430f1e..0d579293c4 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -279,6 +279,9 @@ pub struct Session { /// What a [`cmd::TraceRun`] traced, until the next `imageTrace.make` or /// `imageTrace.makeAndExpand` takes it ([`cmd::Traced::hand_in`]). pub(crate) trace_hand_off: Option, + /// The installed fonts a [`cmd::RetypeSearch`] found, until the next `type.retype` or + /// `type.retypeFonts` takes it ([`cmd::RetypeFound::hand_in`]). + pub(crate) retype_hand_off: Option, /// Whether a click or drag of the place cursor asks the frontend to place its file /// ([`UiRequest::Place`]) instead of running `file.place`: the desktop app sets it to read the /// file off the UI thread. False: the file is placed at once. diff --git a/crates/engine/src/session/documents.rs b/crates/engine/src/session/documents.rs index 61dbdb4491..cfe7810c78 100644 --- a/crates/engine/src/session/documents.rs +++ b/crates/engine/src/session/documents.rs @@ -127,6 +127,7 @@ impl Session { place_queue_loads: 0, image_hand_off: None, trace_hand_off: None, + retype_hand_off: None, place_cursor_requests: false, package_hand_off: None, screens_hand_off: None, diff --git a/crates/text/src/fontdb.rs b/crates/text/src/fontdb.rs index b7efa856c8..4008705a5f 100644 --- a/crates/text/src/fontdb.rs +++ b/crates/text/src/fontdb.rs @@ -27,6 +27,7 @@ mod dirs; mod face; mod glyph_pen; mod gsub; +mod installed; mod lookup; mod names; mod scan; @@ -59,6 +60,7 @@ pub(crate) use face::PathAlignHeights; pub use face::{FALLBACK_FAMILY, FontFace, IcfMargins, OutlineFormat}; pub(crate) use glyph_pen::FlipPen; pub use gsub::{GlyphCategory, GlyphCategoryKind, GlyphOrigin, JoiningPosition, Substitution, SubstitutionKind}; +pub use installed::InstalledFace; #[cfg(not(target_arch = "wasm32"))] use names::SysFallback; #[cfg(test)] diff --git a/crates/text/src/fontdb/installed.rs b/crates/text/src/fontdb/installed.rs new file mode 100644 index 0000000000..fd0fff2382 --- /dev/null +++ b/crates/text/src/fontdb/installed.rs @@ -0,0 +1,167 @@ +//! Installed faces that nothing has loaded yet, read for one search without adding them to the +//! database (Retype's matching, `vectorcraft_text::retype`). + +#[cfg(not(target_arch = "wasm32"))] +use super::build::make_face; +#[cfg(not(target_arch = "wasm32"))] +use super::face::FontBytes; +#[cfg(not(target_arch = "wasm32"))] +use super::scan::enumerate_faces; +use super::{Arc, FontDb, FontFace, Path, PathBuf}; + +/// One style of an installed family that is not loaded: no loaded face has its family and style. +#[derive(Clone, Debug, PartialEq)] +pub struct InstalledFace { + pub family: String, + pub style: String, + /// The font file holding it (a suitcase font's file, whose fonts are in its resource fork). + pub path: PathBuf, + /// The file's length in bytes (a suitcase font's resource fork's), when the scan read it. + pub len: u64, +} + +impl FontDb { + /// The installed faces no loaded face has the family and style of, by family name and then + /// style, as the font scan cataloged them. Reading the list reads no font file. Empty on wasm, + /// where no fonts are installed. + pub fn unloaded_installed_faces(&self) -> Vec { + #[cfg(not(target_arch = "wasm32"))] + { + // The catalog first: the first scan takes the faces' lock, which a guard held here would block. + let cataloged: Vec<(String, String, PathBuf)> = + self.read_catalog().values().flat_map(|c| c.faces.iter().map(|cf| (c.name.clone(), cf.style.clone(), cf.path.clone()))).collect(); + let unloaded: Vec<(String, String, PathBuf)> = { + let loaded = self.read_faces(); + let is_loaded = + |family: &str, style: &str| loaded.iter().any(|f| f.family.eq_ignore_ascii_case(family) && f.style.eq_ignore_ascii_case(style)); + cataloged.into_iter().filter(|(family, style, _)| !is_loaded(family, style)).collect() + }; + let mut out: Vec = + unloaded.into_iter().map(|(family, style, path)| InstalledFace { family, style, len: file_len(&path), path }).collect(); + out.sort_by(|a, b| { + a.family + .to_lowercase() + .cmp(&b.family.to_lowercase()) + .then_with(|| a.style.to_lowercase().cmp(&b.style.to_lowercase())) + .then(a.path.cmp(&b.path)) + }); + out + } + #[cfg(target_arch = "wasm32")] + { + vec![] + } + } + + /// The faces in the font file at `path` (a suitcase font's in its resource fork), read for one + /// search and not added to the database: none when the file, or the fork, is longer than + /// `max_len` bytes or holds no font. Each face read has an id of its own, which no loaded face + /// has, and its path is `path`. Empty on wasm. + pub fn read_unloaded_file(&self, path: &Path, max_len: u64) -> Vec> { + #[cfg(not(target_arch = "wasm32"))] + { + let files = if crate::suitcase::is_suitcase(path) { + if crate::suitcase::fork_len(path) > max_len { + return vec![]; + } + crate::suitcase::read_fonts(path) + } else { + read_within(path, max_len).into_iter().collect() + }; + let mut out = vec![]; + for data in files { + let data = Arc::new(data); + for (i, spec) in enumerate_faces(&data) { + if let Some(f) = make_face(FontBytes::Owned(data.clone()), i, spec, Some(path.to_path_buf())) { + out.push(Arc::new(f)); + } + } + } + out + } + #[cfg(target_arch = "wasm32")] + { + let _ = (path, max_len); + vec![] + } + } +} + +impl FontDb { + /// Load `face`, a face [`Self::read_unloaded_file`] read, without reading its file again or + /// the family's other files: it joins the loaded faces, unless a face of its family, style and + /// version is loaded already, which is returned instead. + pub fn load_read_face(&self, face: Arc) -> Arc { + let same = + |f: &FontFace| f.family.eq_ignore_ascii_case(&face.family) && f.style.eq_ignore_ascii_case(&face.style) && f.version == face.version; + let mut faces = self.faces.write().unwrap_or_else(std::sync::PoisonError::into_inner); + if let Some(f) = faces.iter().find(|f| same(f)) { + return f.clone(); + } + faces.push(face.clone()); + drop(faces); + self.changed(); + face + } +} + +/// The length of the font file at `path`, or of its resource fork for a suitcase font; 0 when it +/// cannot be read. +#[cfg(not(target_arch = "wasm32"))] +fn file_len(path: &Path) -> u64 { + match std::fs::metadata(path) { + Ok(m) if m.len() == 0 => crate::suitcase::fork_len(path), + Ok(m) => m.len(), + Err(_) => 0, + } +} + +/// The file at `path`, when it is at most `max_len` bytes long (read no further than one byte past). +#[cfg(not(target_arch = "wasm32"))] +fn read_within(path: &Path, max_len: u64) -> Option> { + use std::io::Read; + let mut data = Vec::new(); + std::fs::File::open(path).ok()?.take(max_len.saturating_add(1)).read_to_end(&mut data).ok()?; + (data.len() as u64 <= max_len).then_some(data) +} + +#[cfg(test)] +#[cfg(not(target_arch = "wasm32"))] +mod tests { + use super::*; + + /// A database whose catalog holds the bundled font files, with Inter's faces dropped from the + /// loaded ones: Inter is installed and not loaded. + fn inter_unloaded() -> FontDb { + let dir = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../assets/fonts"); + let db = FontDb::with_font_dirs(vec![dir]); + db.faces.write().unwrap().retain(|f| f.family != "Inter"); + db + } + + #[test] + fn installed_faces_not_loaded_are_listed_and_read_without_loading_them() { + let db = inter_unloaded(); + let list = db.unloaded_installed_faces(); + let inter: Vec<&InstalledFace> = list.iter().filter(|f| f.family == "Inter").collect(); + assert!(inter.iter().any(|f| f.style == "Regular"), "{list:?}"); + // The loaded families are not listed. + assert!(!list.iter().any(|f| f.family == "Source Sans 3"), "{list:?}"); + let regular = inter.iter().find(|f| f.style == "Regular").unwrap(); + assert_eq!(regular.len, std::fs::metadata(®ular.path).unwrap().len()); + let before = db.loaded_faces().len(); + let read = db.read_unloaded_file(®ular.path, regular.len); + assert!(read.iter().any(|f| f.family == "Inter" && f.style == "Regular"), "the file's face is read"); + assert!(read.iter().all(|f| f.path() == Some(regular.path.as_path()))); + // Read for the search only: the database does not hold it, and no loaded face has its id. + assert_eq!(db.loaded_faces().len(), before); + assert!(read.iter().all(|f| db.face_by_id(f.id()).is_none())); + assert!(db.unloaded_installed_faces().iter().any(|f| f.family == "Inter"), "still not loaded"); + // A file longer than the limit is not read. + assert!(db.read_unloaded_file(®ular.path, regular.len - 1).is_empty()); + assert!(db.read_unloaded_file(®ular.path.with_extension("missing"), u64::MAX).is_empty()); + // Once loaded, the family is no longer listed. + assert!(db.face("Inter", "Regular").is_some_and(|f| f.family == "Inter")); + assert!(!db.unloaded_installed_faces().iter().any(|f| f.family == "Inter" && f.style == "Regular")); + } +} diff --git a/crates/text/src/lib.rs b/crates/text/src/lib.rs index 7b70b9c5a2..bddb446484 100644 --- a/crates/text/src/lib.rs +++ b/crates/text/src/lib.rs @@ -43,7 +43,7 @@ pub use features::{ }; pub use fontdb::{ CompositeCoverage, FALLBACK_FAMILY, FontClass, FontDb, FontFace, FontLikeness, FontMatch, FontTraits, GENERIC_FAMILIES, GlyphAlternate, - GlyphCategory, GlyphCategoryKind, GlyphOrigin, IcfMargins, JoiningPosition, LentCompositeFonts, OutlineFormat, PlatformFontFiles, + GlyphCategory, GlyphCategoryKind, GlyphOrigin, IcfMargins, InstalledFace, JoiningPosition, LentCompositeFonts, OutlineFormat, PlatformFontFiles, RECENTLY_ADDED_WITHIN, RecentlyAdded, StylisticSet, Substitution, SubstitutionKind, WantedFont, WantedFonts, app_font_dir, is_font_file, is_generic_family, is_suitcase, set_app_font_dir, set_platform_font_files, set_user_font_dirs, set_user_font_dirs_confined, style_weight, system_font_dirs, user_font_dirs, diff --git a/crates/text/src/retype.rs b/crates/text/src/retype.rs index d7c7be71d6..901403f341 100644 --- a/crates/text/src/retype.rs +++ b/crates/text/src/retype.rs @@ -153,6 +153,32 @@ impl RetypeIndex { } } } + Self::indexed(kept, entries) + } + + /// Index the outline glyphs of `face`, a face read for one search and not loaded + /// ([`FontDb::read_unloaded_file`]), whose [`shape_key`] is in `keys`, as [`Self::build`] + /// does. The face's keys are not kept for a later search, so the keys of loaded faces stay + /// kept. Each of its encoded glyphs ([`encoded_glyphs`]) is drawn once, for its key and its sampling both. + pub fn build_unloaded(db: &FontDb, face: Arc, keys: &BTreeSet) -> Self { + let mut entries = vec![]; + for (gid, ch) in matched_glyphs(&face) { + if entries.len() >= MAX_GLYPHS { + break; + } + let outline = db.outline_uncached(&face, gid); + if !shape_key(&outline).is_some_and(|key| keys.contains(&key)) { + continue; + } + if let Some(sig) = signatures(&outline, false).into_iter().next() { + entries.push(Entry { face: 0, gid, ch, sig, outline }); + } + } + Self::indexed(vec![face], entries) + } + + /// The index of `entries`, glyphs of `kept`. + fn indexed(kept: Vec>, entries: Vec) -> Self { let mut buckets: HashMap> = HashMap::new(); for (i, e) in entries.iter().enumerate() { buckets.entry(e.sig.contours).or_default().push(i); @@ -297,16 +323,7 @@ fn face_keys(db: &FontDb, face: &FontFace) -> FaceKeys { return keys.clone(); } } - let mut by_gid: HashMap = HashMap::new(); - for &(c, gid) in face.mapped_chars().iter().take(MAX_GLYPHS_PER_FACE) { - if c.is_whitespace() || c.is_control() || is_shape_symbol(c) { - continue; - } - by_gid.entry(gid).and_modify(|e| *e = (*e).min(c)).or_insert(c); - } - let mut gids: Vec<(u32, char)> = by_gid.into_iter().collect(); - gids.sort_unstable(); - let keys: FaceKeys = Arc::new(gids.into_iter().filter_map(|(gid, ch)| Some((gid, ch, shape_key(&db.outline_uncached(face, gid))?))).collect()); + let keys = read_keys(db, face); let mut k = kept.lock().unwrap_or_else(|e| e.into_inner()); if k.generation != generation { return keys; @@ -322,6 +339,33 @@ fn face_keys(db: &FontDb, face: &FontFace) -> FaceKeys { keys } +/// The glyphs of `face` that are matched, under the lowest character that maps to each: its +/// encoded characters (the first [`MAX_GLYPHS_PER_FACE`]) less spaces, controls and +/// [`is_shape_symbol`]s. +fn matched_glyphs(face: &FontFace) -> Vec<(u32, char)> { + let mut by_gid: HashMap = HashMap::new(); + for &(c, gid) in face.mapped_chars().iter().take(MAX_GLYPHS_PER_FACE) { + if c.is_whitespace() || c.is_control() || is_shape_symbol(c) { + continue; + } + by_gid.entry(gid).and_modify(|e| *e = (*e).min(c)).or_insert(c); + } + let mut gids: Vec<(u32, char)> = by_gid.into_iter().collect(); + gids.sort_unstable(); + gids +} + +/// How many glyphs of `face` an index draws to read their keys: at most [`MAX_GLYPHS_PER_FACE`]. +/// Reads the face's cmap only. +pub fn encoded_glyphs(face: &FontFace) -> usize { + face.mapped_chars().len().min(MAX_GLYPHS_PER_FACE) +} + +/// [`FaceKeys`] of `face`, each matched glyph drawn once, past the outline cache. +fn read_keys(db: &FontDb, face: &FontFace) -> FaceKeys { + Arc::new(matched_glyphs(face).into_iter().filter_map(|(gid, ch)| Some((gid, ch, shape_key(&db.outline_uncached(face, gid))?))).collect()) +} + /// Characters whose glyphs are plain shapes (box drawing, blocks, geometric shapes, legacy /// computing symbols) or a font's own icons (private use): a drawn rectangle or circle is the same /// shape as one of them, so matching them would turn art into text. They are not matched. @@ -595,6 +639,20 @@ pub fn shape_key(path: &BezPath) -> Option { Some(h) } +/// Is `path` a plain shape: one contour of at most [`PLAIN_EDGES`] straight edges, as +/// [`contours`] reads it (a rectangle, a triangle, a bar)? Many fonts have a glyph of such a shape +/// (a hyphen, a bar, a mark), so it does not tell which font outlined text is in. `false` for an +/// empty shape or one past the size caps. +pub fn is_plain(path: &BezPath) -> bool { + match contours(path).as_deref() { + Some([c]) => c.len() <= PLAIN_EDGES && c.iter().all(|s| matches!(s, PathSeg::Line(_))), + _ => false, + } +} + +/// The most straight edges of a plain shape ([`is_plain`]). +const PLAIN_EDGES: usize = 4; + /// `path` read for matching: one reading per choice of starting corners (the corner of each contour /// farthest from the centre of all the shape's corners; every tied corner when `all_ties`, else the /// first), at most [`MAX_VARIANTS`] tried. Empty for a shape with nothing to match. @@ -942,4 +1000,51 @@ mod tests { index.matches(&shape).iter().map(|m| m.face.id()).collect::>() ); } + + #[test] + fn plain_shapes_are_one_contour_of_up_to_four_straight_edges() { + let rect = kurbo::Rect::new(0.0, 0.0, 80.0, 40.0).to_path(0.1); + assert!(is_plain(&rect)); + let mut triangle = BezPath::new(); + triangle.move_to((0.0, 0.0)); + triangle.line_to((50.0, 0.0)); + // A straight edge split in two reads as one. + triangle.line_to((50.0, 20.0)); + triangle.line_to((50.0, 40.0)); + triangle.close_path(); + assert!(is_plain(&triangle)); + let mut pentagon = BezPath::new(); + pentagon.move_to((0.0, 0.0)); + for p in [(40.0, 0.0), (50.0, 30.0), (20.0, 50.0), (-10.0, 30.0)] { + pentagon.line_to(p); + } + pentagon.close_path(); + assert!(!is_plain(&pentagon)); + assert!(!is_plain(&kurbo::Circle::new((0.0, 0.0), 10.0).to_path(0.1)), "curves"); + assert!(!is_plain(&letter()), "two contours"); + assert!(!is_plain(&BezPath::new())); + } + + /// A face read from an installed file and not loaded is indexed as a loaded one is, and the + /// count of glyphs its index draws comes from its cmap. + #[cfg(not(target_arch = "wasm32"))] + #[test] + fn an_unloaded_face_is_indexed_as_a_loaded_one() { + let dir = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../assets/fonts"); + let db = FontDb::with_font_dirs(vec![]); + let loaded = db.face("Source Sans 3", "Regular").unwrap(); + let read = db.read_unloaded_file(&dir.join("SourceSans3-Regular.ttf"), u64::MAX); + let face = read.into_iter().find(|f| f.family == "Source Sans 3").unwrap(); + assert_ne!(face.id(), loaded.id()); + assert_eq!(encoded_glyphs(&face), face.mapped_chars().len().min(MAX_GLYPHS_PER_FACE)); + let shape = Affine::translate((40.0, 90.0)) * Affine::scale(0.03) * db.outline_uncached(&face, face.glyph_for('g')); + let keys: BTreeSet = std::iter::once(shape_key(&shape).unwrap()).collect(); + let unloaded = RetypeIndex::build_unloaded(&db, face.clone(), &keys); + let built = RetypeIndex::build(&db, [loaded.clone()], &keys); + assert_eq!(unloaded.len(), built.len()); + let (a, b) = (unloaded.matches(&shape), built.matches(&shape)); + assert_eq!(a.first().map(|m| (m.face.id(), m.ch)), Some((face.id(), 'g'))); + assert_eq!(b.first().map(|m| m.ch), Some('g')); + assert!(a.first().unwrap().origin.distance(b.first().unwrap().origin) < 1e-9); + } } diff --git a/crates/ui-egui/src/app.rs b/crates/ui-egui/src/app.rs index bba6a5d83d..3789fe5a10 100644 --- a/crates/ui-egui/src/app.rs +++ b/crates/ui-egui/src/app.rs @@ -11,8 +11,8 @@ use super::state::{ use super::{ Arc, AutomationRoots, ControlRequest, Ordering, Receiver, Session, UiState, Value, VectorcraftApp, View, ViewInfo, background, canvas, chrome, clipboard_probe, dialogs, export_progress, file_access, fileio, font_menu, graphics, i18n, io, json, menus, native_menu, opening, palette, - panel_docking, panels, picks, place, placing, plugin_runs, prefs_dialog, recovery, screen_color, scrub, shortcut_editor, shortcuts, theme, - titlebar, toolbar, tools_float, trace_runs, unsaved, updates_ui, widgets, + panel_docking, panels, picks, place, placing, plugin_runs, prefs_dialog, recovery, retype_runs, screen_color, scrub, shortcut_editor, shortcuts, + theme, titlebar, toolbar, tools_float, trace_runs, unsaved, updates_ui, widgets, }; mod clipboard; @@ -165,6 +165,7 @@ impl VectorcraftApp { plugin_runs: Default::default(), placing: Default::default(), trace_runs: Default::default(), + retype_runs: Default::default(), toasts: Default::default(), recovery: Default::default(), host_modifiers: Default::default(), @@ -270,6 +271,7 @@ impl VectorcraftApp { plugin_runs::poll(self); trace_runs::poll(self); placing::poll(self); + retype_runs::poll(self); } /// The language the UI is drawn in: the Preferences dialog's choice while it is open (so a @@ -388,6 +390,7 @@ impl VectorcraftApp { || !self.plugin_runs.running.is_empty() || !self.placing.pending.is_empty() || !self.trace_runs.running.is_empty() + || self.retype_runs.running.is_some() { // Keep the status bar's progress moving and pick the result up when it arrives. ctx.request_repaint_after(std::time::Duration::from_millis(100)); @@ -645,6 +648,7 @@ impl VectorcraftApp { trace_runs::show(self, &ctx); opening::show(self, &ctx); placing::show(self, &ctx); + retype_runs::show(self, &ctx); // After every window this pass may open, and before the palette's field takes the keyboard. panel_docking::close_overlays_for_modal(self, &ctx); palette::show(self, &ctx); diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index e4271f7926..e7b5b805a9 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -1886,6 +1886,7 @@ digits Malayalam Malaiàlam Reset Retype Panel Restableix el panell Torna a escriure List Matching Fonts Llista els tipus de lletra coincidents Retype Preview Previsualització del panell Torna a escriure +@msg `installed` must be true, false or null `installed` ha de ser true, false o null @msg `count` must be a whole number from 1 to 96 `count` ha de ser un nombre enter entre 1 i 96 @msg `size` must be small, medium or large `size` ha de ser small, medium o large @msg `text` must be a string of at most 100 characters `text` ha de ser una cadena de 100 caràcters com a màxim @@ -7648,6 +7649,7 @@ variable-list-end {0}, {1} {0} i {1} @msg {_1} files {_1} fitxers @msg {_1} files are written by file.saveAsTemplate els fitxers {_1} els escriu file.saveAsTemplate @msg {_1} files can be opened but not written (see document.formats) els fitxers {_1} es poden obrir però no escriure (consulta document.formats) +@msg Retype finished, but the document or its selection changed meanwhile: run it again Torna a escriure ha acabat, però el document o la seva selecció ha canviat mentrestant: torna-ho a executar @msg {_1} finished, but the document or the plug-in changed meanwhile: run it again {_1} ha acabat, però el document o el complement ha canviat mentrestant: torna-ho a executar @msg {_1} font families available {_1} famílies de tipus de lletra disponibles @msg {_1} has no {_2} style {_1} no té cap estil {_2} diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index 488df173c3..52bf5c3c2c 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -460,6 +460,7 @@ Reset Retype Panel Obnovit panel Přepsat List Matching Fonts Vypsat odpovídající písma Retype Preview Náhled v panelu Přepsat +@msg `installed` must be true, false or null `installed` musí být true, false nebo null @msg `count` must be a whole number from 1 to 96 `count` musí být celé číslo od 1 do 96 @msg `size` must be small, medium or large `size` musí být small, medium nebo large @msg `text` must be a string of at most 100 characters `text` musí být řetězec o nejvýše 100 znacích @@ -8938,6 +8939,7 @@ breakText Glyphs Glyfy @msg Image Trace failed: internal error: its thread stopped (please report this bug) Vektorizace obrazu selhala: vnitřní chyba: její vlákno se zastavilo (nahlaste prosím tuto chybu) @msg Image Trace failed: {e} Vektorizace obrazu selhala: {e} @msg Image Trace finished, but its document was closed Vektorizace obrazu skončila, ale její dokument byl zavřen +@msg Retype finished, but the document or its selection changed meanwhile: run it again Přepsání skončilo, ale dokument nebo jeho výběr se mezitím změnil: spusťte ho znovu @msg Image Trace finished, but the image or its settings changed meanwhile: trace it again Vektorizace obrazu skončila, ale obraz nebo jeho nastavení se mezitím změnily: vektorizujte ho znovu @msg Image Trace finished, but its document was reverted: trace it again Vektorizace obrazu skončila, ale její dokument byl vrácen k uložené verzi: vektorizujte ho znovu @msg Import SVG Filter reads SVG files, not SVGZ Importovat filtr SVG čte soubory SVG, ne SVGZ diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index 302ab6aa69..cb8e37b4fb 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -1010,6 +1010,7 @@ liquify-list-end {0}, {1} {0} og {1} @msg Image Trace failed: {e} Billedsporing mislykkedes: {e} @msg Image Trace finished, but its document was closed Billedsporing blev færdig, men dens dokument blev lukket @msg Image Trace finished, but its document was reverted: trace it again Billedsporing blev færdig, men dens dokument blev gendannet: spor det igen +@msg Retype finished, but the document or its selection changed meanwhile: run it again Genindtast blev færdig, men dokumentet eller dets markering ændrede sig imens: kør det igen @msg Image Trace finished, but the image or its settings changed meanwhile: trace it again Billedsporing blev færdig, men billedet eller dets indstillinger ændrede sig imens: spor det igen @msg Import SVG Filter reads SVG files, not SVGZ Importér SVG-filter læser SVG-filer, ikke SVGZ @msg Invalid dimension offset Ugyldig forskydning af målet @@ -3181,6 +3182,7 @@ liquify-list-end {0}, {1} {0} og {1} Reset Retype Panel Nulstil panelet Genindtast List Matching Fonts Vis matchende skrifttyper Retype Preview Forhåndsvisning i panelet Genindtast +@msg `installed` must be true, false or null `installed` skal være true, false eller null @msg `count` must be a whole number from 1 to 96 `count` skal være et heltal fra 1 til 96 @msg `size` must be small, medium or large `size` skal være small, medium eller large @msg `text` must be a string of at most 100 characters `text` skal være en streng på højst 100 tegn diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index 9482345f18..64d064bd4c 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -1383,6 +1383,7 @@ font-technology Variable Variabel Reset Retype Panel Bedienfeld „Neu setzen“ zurücksetzen List Matching Fonts Passende Schriften auflisten Retype Preview Vorschau im Bedienfeld „Neu setzen“ +@msg `installed` must be true, false or null `installed` muss true, false oder null sein @msg `count` must be a whole number from 1 to 96 `count` muss eine ganze Zahl von 1 bis 96 sein @msg `size` must be small, medium or large `size` muss small, medium oder large sein @msg `text` must be a string of at most 100 characters `text` muss eine Zeichenfolge mit höchstens 100 Zeichen sein @@ -8822,6 +8823,7 @@ breakText Glyphs Glyphen @msg Image Trace failed: internal error: its thread stopped (please report this bug) Bildnachzeichner fehlgeschlagen: interner Fehler: Sein Thread wurde beendet (bitte melden Sie diesen Fehler) @msg Image Trace failed: {e} Bildnachzeichner fehlgeschlagen: {e} @msg Image Trace finished, but its document was closed Bildnachzeichner abgeschlossen, aber sein Dokument wurde geschlossen +@msg Retype finished, but the document or its selection changed meanwhile: run it again Neu setzen abgeschlossen, aber das Dokument oder seine Auswahl hat sich inzwischen geändert: Führen Sie es erneut aus @msg Image Trace finished, but the image or its settings changed meanwhile: trace it again Bildnachzeichner abgeschlossen, aber das Bild oder seine Einstellungen haben sich inzwischen geändert: Zeichnen Sie es erneut nach @msg Image Trace finished, but its document was reverted: trace it again Bildnachzeichner abgeschlossen, aber sein Dokument wurde auf die letzte Version zurückgesetzt: Zeichnen Sie es erneut nach @msg Invalid dimension offset Ungültiger Bemaßungsversatz diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index 434d0cc0b8..71b62d4adf 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -1327,6 +1327,7 @@ font-technology Variable Μεταβλητές Reset Retype Panel Επαναφορά πίνακα Επαναπληκτρολόγησης List Matching Fonts Λίστα αντίστοιχων γραμματοσειρών Retype Preview Προεπισκόπηση πίνακα Επαναπληκτρολόγησης +@msg `installed` must be true, false or null Το `installed` πρέπει να είναι true, false ή null @msg `count` must be a whole number from 1 to 96 Το `count` πρέπει να είναι ακέραιος από 1 έως 96 @msg `size` must be small, medium or large Το `size` πρέπει να είναι small, medium ή large @msg `text` must be a string of at most 100 characters Το `text` πρέπει να είναι συμβολοσειρά έως 100 χαρακτήρων @@ -7284,6 +7285,7 @@ axis Y Axis Άξονας Y The plug-in is computing… Το πρόσθετο υπολογίζει… Inspect Plug-in Επιθεώρηση προσθέτου Cancel Plug-in Run Ακύρωση εκτέλεσης προσθέτου +@msg Retype finished, but the document or its selection changed meanwhile: run it again Η Επαναπληκτρολόγηση ολοκληρώθηκε, αλλά το έγγραφο ή η επιλογή του άλλαξε στο μεταξύ: εκτελέστε την ξανά @msg {_1} finished, but the document or the plug-in changed meanwhile: run it again Το {_1} ολοκληρώθηκε, αλλά το έγγραφο ή το πρόσθετο άλλαξε στο μεταξύ: εκτελέστε το ξανά @msg Running “{name}”… Εκτέλεση του «{name}»… @msg a live effect runs while the document is drawn, so it can't be `heavy` ένα δυναμικό εφέ εκτελείται κατά τη σχεδίαση του εγγράφου, οπότε δεν μπορεί να είναι `heavy` diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index 3f83e928e4..3619c9fff8 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -1407,6 +1407,7 @@ font-technology Variable Variables Reset Retype Panel Restablecer panel Reescribir List Matching Fonts Enumerar fuentes coincidentes Retype Preview Vista previa del panel Reescribir +@msg `installed` must be true, false or null `installed` debe ser true, false o null @msg `count` must be a whole number from 1 to 96 `count` debe ser un número entero entre 1 y 96 @msg `size` must be small, medium or large `size` debe ser small, medium o large @msg `text` must be a string of at most 100 characters `text` debe ser una cadena de 100 caracteres como máximo @@ -9266,6 +9267,7 @@ breakText Glyphs Glifos @msg Image Trace failed: internal error: its thread stopped (please report this bug) Error de Calco de imagen: error interno: su hilo se detuvo (informa de este error) @msg Image Trace failed: {e} Error de Calco de imagen: {e} @msg Image Trace finished, but its document was closed Calco de imagen terminó, pero su documento se cerró +@msg Retype finished, but the document or its selection changed meanwhile: run it again Reescribir terminó, pero el documento o su selección cambiaron mientras tanto: ejecútalo de nuevo @msg Image Trace finished, but the image or its settings changed meanwhile: trace it again Calco de imagen terminó, pero la imagen o sus ajustes cambiaron mientras tanto: cálcala de nuevo @msg Invalid dimension offset Desplazamiento de cota no válido @msg Invalid point Punto no válido diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index a4d85b23e8..88edeba695 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -457,6 +457,7 @@ Reset Retype Panel Palauta Kirjoita uudelleen -paneeli List Matching Fonts Luettele vastaavat fontit Retype Preview Kirjoita uudelleen -paneelin esikatselu +@msg `installed` must be true, false or null `installed` on oltava true, false tai null @msg `count` must be a whole number from 1 to 96 `count` on oltava kokonaisluku 1–96 @msg `size` must be small, medium or large `size` on oltava small, medium tai large @msg `text` must be a string of at most 100 characters `text` on oltava enintään 100 merkin merkkijono @@ -7361,6 +7362,7 @@ axis Y Axis Y-akseli The plug-in is computing… Laajennus laskee… Inspect Plug-in Tarkastele laajennusta Cancel Plug-in Run Peruuta laajennuksen ajo +@msg Retype finished, but the document or its selection changed meanwhile: run it again Kirjoita uudelleen valmistui, mutta asiakirja tai sen valinta muuttui sillä välin: suorita se uudelleen @msg {_1} finished, but the document or the plug-in changed meanwhile: run it again {_1} valmistui, mutta asiakirja tai laajennus muuttui sillä välin: suorita se uudelleen @msg Running “{name}”… Suoritetaan ”{name}”… @msg a live effect runs while the document is drawn, so it can't be `heavy` live-tehoste suoritetaan asiakirjaa piirrettäessä, joten se ei voi olla `heavy` diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 8f56486157..3581a0a211 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -1397,6 +1397,7 @@ font-technology Variable Variables Reset Retype Panel Réinitialiser le panneau Retaper List Matching Fonts Lister les polices correspondantes Retype Preview Aperçu du panneau Retaper +@msg `installed` must be true, false or null `installed` doit valoir true, false ou null @msg `count` must be a whole number from 1 to 96 `count` doit être un nombre entier compris entre 1 et 96 @msg `size` must be small, medium or large `size` doit valoir small, medium ou large @msg `text` must be a string of at most 100 characters `text` doit être une chaîne d’au plus 100 caractères @@ -8807,6 +8808,7 @@ breakText Glyphs Glyphes @msg Image Trace failed: {e} Échec de la vectorisation de l’image : {e} @msg Image Trace finished, but its document was closed La vectorisation de l’image est terminée, mais son document a été fermé @msg Image Trace finished, but its document was reverted: trace it again La vectorisation de l’image est terminée, mais son document a été rétabli à la version précédente : vectorisez-la à nouveau +@msg Retype finished, but the document or its selection changed meanwhile: run it again Retaper est terminé, mais le document ou sa sélection a changé entre-temps. Relancez-le @msg Image Trace finished, but the image or its settings changed meanwhile: trace it again La vectorisation de l’image est terminée, mais l’image ou ses réglages ont changé entre-temps : vectorisez-la à nouveau @msg Import SVG Filter reads SVG files, not SVGZ Importer un filtre SVG lit les fichiers SVG, pas SVGZ @msg Invalid dimension offset Décalage de cote non valide diff --git a/crates/ui-egui/src/i18n/hi.tsv b/crates/ui-egui/src/i18n/hi.tsv index e9509d9202..4ddb098c1a 100644 --- a/crates/ui-egui/src/i18n/hi.tsv +++ b/crates/ui-egui/src/i18n/hi.tsv @@ -2333,6 +2333,7 @@ arrowhead Feather पंख Reset Retype Panel फिर से टाइप करें पैनल रीसेट करें List Matching Fonts मिलते-जुलते फ़ॉन्ट की सूची Retype Preview फिर से टाइप करें पैनल का प्रीव्यू +@msg `installed` must be true, false or null `installed` को true, false या null होना चाहिए @msg `count` must be a whole number from 1 to 96 `count` 1 से 96 तक पूरी संख्या होना चाहिए @msg `size` must be small, medium or large `size` को small, medium या large होना चाहिए @msg `text` must be a string of at most 100 characters `text` अधिकतम 100 वर्णों की स्ट्रिंग होनी चाहिए @@ -8066,6 +8067,7 @@ liquify-list-end {0}, {1} {0} और {1} @msg Image Trace failed: {e} इमेज ट्रेस विफल: {e} @msg Image Trace failed: internal error: its thread stopped (please report this bug) इमेज ट्रेस विफल: आंतरिक त्रुटि: इसके धागे को बंद कर दिया (कृपया इस बग की रिपोर्ट करें) @msg Image Trace finished, but its document was closed इमेज ट्रेस समाप्त हो गया, लेकिन इसका डॉक्यूमेंट बंद हो गया। +@msg Retype finished, but the document or its selection changed meanwhile: run it again फिर से टाइप करना समाप्त हो गया, लेकिन इस बीच दस्तावेज़ या उसका चयन बदल गया: इसे फिर से चलाएँ @msg Image Trace finished, but the image or its settings changed meanwhile: trace it again इमेज ट्रेस समाप्त हो गया, लेकिन इस बीच इमेज या इसकी सेटिंग्स बदल गई: इसे फिर से ट्रेस करें @msg Image Trace finished, but its document was reverted: trace it again इमेज ट्रेस समाप्त हो गया, लेकिन इसके डॉक्यूमेंट को मूल स्थिति में लाया गया: इसे फिर से ट्रेस करें @msg Image Trace: the traced image is missing इमेज ट्रेस: ज्ञात इमेज गायब है diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index 87f050ef0d..393720cd19 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -1742,6 +1742,7 @@ digits Malayalam Malajálam Reset Retype Panel Újragépelés panel visszaállítása List Matching Fonts Egyező betűtípusok listázása Retype Preview Újragépelés panel előnézete +@msg `installed` must be true, false or null `installed`: true, false vagy null kell @msg `count` must be a whole number from 1 to 96 `count`: 1 és 96 közötti egész szám kell @msg `size` must be small, medium or large `size`: small, medium vagy large kell @msg `text` must be a string of at most 100 characters `text`: legfeljebb 100 karakteres karakterlánc kell @@ -8809,6 +8810,7 @@ breakText Glyphs Glifák @msg Image Trace failed: internal error: its thread stopped (please report this bug) A képvektorizálás nem sikerült: belső hiba: a szála leállt (kérjük, jelentsd ezt a hibát) @msg Image Trace failed: {e} A képvektorizálás nem sikerült: {e} @msg Image Trace finished, but its document was closed A képvektorizálás elkészült, de a dokumentumát bezárták +@msg Retype finished, but the document or its selection changed meanwhile: run it again Az újragépelés elkészült, de a dokumentum vagy a kijelölése közben megváltozott: futtasd újra @msg Image Trace finished, but the image or its settings changed meanwhile: trace it again A képvektorizálás elkészült, de a kép vagy a beállításai közben megváltoztak: vektorizáld újra @msg Image Trace finished, but its document was reverted: trace it again A képvektorizálás elkészült, de a dokumentumát visszaállították a mentett változatra: vektorizáld újra @msg Import SVG Filter reads SVG files, not SVGZ Az SVG-szűrő importálása SVG-fájlokat olvas, SVGZ-fájlokat nem diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index 924d3d80b5..b7ef9a298e 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -409,6 +409,7 @@ @msg `spread` must be pad, repeat or reflect `spread` harus pad, repeat atau reflect @msg `repeats` must be a whole number from 1 to {MAX_REPEATS} `repeats` harus berupa bilangan bulat dari 1 sampai {MAX_REPEATS} @msg `spread` applies to linear, radial, conic and diamond gradients `spread` berlaku untuk gradien linear, radial, conic, dan diamond +@msg Retype finished, but the document or its selection changed meanwhile: run it again Ketik Ulang selesai, tetapi dokumen atau pilihannya berubah sementara itu: jalankan lagi @msg {_1} finished, but the document or the plug-in changed meanwhile: run it again {_1} selesai, tetapi dokumen atau plug-in berubah sementara itu: jalankan lagi @msg Running “{name}”… Menjalankan “{name}”… @msg a live effect runs while the document is drawn, so it can't be `heavy` efek langsung berjalan saat dokumen digambar, sehingga tidak dapat `heavy` @@ -1058,6 +1059,7 @@ Reset Retype Panel Setel ulang panel Ketik Ulang List Matching Fonts Daftar font yang cocok Retype Preview Pratinjau panel Ketik Ulang +@msg `installed` must be true, false or null `installed` harus true, false, atau null @msg `count` must be a whole number from 1 to 96 `count` harus bilangan bulat dari 1 sampai 96 @msg `size` must be small, medium or large `size` harus small, medium, atau large @msg `text` must be a string of at most 100 characters `text` harus string dengan paling banyak 100 karakter diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index 5f47e3f117..59a068be66 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -1420,6 +1420,7 @@ font-technology Variable Variabili Reset Retype Panel Reimposta pannello Ridigita List Matching Fonts Elenca font corrispondenti Retype Preview Anteprima del pannello Ridigita +@msg `installed` must be true, false or null `installed` deve essere true, false o null @msg `count` must be a whole number from 1 to 96 `count` deve essere un numero intero compreso tra 1 e 96 @msg `size` must be small, medium or large `size` deve essere small, medium o large @msg `text` must be a string of at most 100 characters `text` deve essere una stringa di al massimo 100 caratteri @@ -8875,6 +8876,7 @@ breakText Glyphs Glifi @msg Image Trace failed: internal error: its thread stopped (please report this bug) Ricalco immagine non riuscito: errore interno: il suo thread si è fermato (segnala questo bug) @msg Image Trace failed: {e} Ricalco immagine non riuscito: {e} @msg Image Trace finished, but its document was closed Ricalco immagine terminato, ma il suo documento è stato chiuso +@msg Retype finished, but the document or its selection changed meanwhile: run it again Ridigita terminato, ma nel frattempo il documento o la sua selezione sono cambiati: eseguilo di nuovo @msg Image Trace finished, but the image or its settings changed meanwhile: trace it again Ricalco immagine terminato, ma nel frattempo l'immagine o le sue impostazioni sono cambiate: ricalcala di nuovo @msg Image Trace finished, but its document was reverted: trace it again Ricalco immagine terminato, ma il suo documento è stato ripristinato: ricalcala di nuovo @msg Invalid dimension offset Distanza della quota non valida diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index 9a1b5f6354..a2b4d8f47a 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -521,6 +521,7 @@ digits Malayalam マラヤーラム数字 Reset Retype Panel リタイプパネルをリセット List Matching Fonts 一致するフォントの一覧 Retype Preview リタイプパネルのプレビュー +@msg `installed` must be true, false or null `installed` には true、false または null を指定してください @msg `count` must be a whole number from 1 to 96 `count` には 1 から 96 の整数を指定してください @msg `size` must be small, medium or large `size` には small、medium、large のいずれかを指定してください @msg `text` must be a string of at most 100 characters `text` には 100 文字以内の文字列を指定してください @@ -7692,6 +7693,7 @@ axis Y Axis Y 軸 @msg Image Trace failed: internal error: its thread stopped (please report this bug) 画像トレースに失敗しました: 内部エラー: スレッドが停止しました (このバグを報告してください) @msg Image Trace failed: {e} 画像トレースに失敗しました: {e} @msg Image Trace finished, but its document was closed 画像トレースは完了しましたが、ドキュメントが閉じられています +@msg Retype finished, but the document or its selection changed meanwhile: run it again リタイプは完了しましたが、その間にドキュメントまたは選択範囲が変更されました: もう一度実行してください @msg Image Trace finished, but the image or its settings changed meanwhile: trace it again 画像トレースは完了しましたが、その間に画像または設定が変更されました: もう一度トレースしてください @msg Image Trace finished, but its document was reverted: trace it again 画像トレースは完了しましたが、ドキュメントは保存済みの状態に戻されました: もう一度トレースしてください @msg Invalid dimension offset 寸法のオフセットが無効です diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index 8eeacee621..2d6269338c 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -89,6 +89,7 @@ @msg Image Trace failed: internal error: its thread stopped (please report this bug) გამოსახულების ვექტორიზაცია ვერ მოხერხდა: შიდა შეცდომა: მისი ნაკადი შეჩერდა (გთხოვთ, შეგვატყობინოთ ამ ხარვეზის შესახებ) @msg Image Trace failed: {e} გამოსახულების ვექტორიზაცია ვერ მოხერხდა: {e} @msg Image Trace finished, but its document was closed გამოსახულების ვექტორიზაცია დასრულდა, მაგრამ მისი დოკუმენტი დაიხურა +@msg Retype finished, but the document or its selection changed meanwhile: run it again ხელახლა აკრეფა დასრულდა, მაგრამ ამასობაში დოკუმენტი ან მისი მონიშვნა შეიცვალა: გაუშვით ხელახლა @msg Image Trace finished, but the image or its settings changed meanwhile: trace it again გამოსახულების ვექტორიზაცია დასრულდა, მაგრამ ამასობაში გამოსახულება ან მისი პარამეტრები შეიცვალა: გაუშვით ვექტორიზაცია ხელახლა @msg Import SVG Filter reads SVG files, not SVGZ „SVG ფილტრის იმპორტი“ კითხულობს SVG ფაილებს და არა SVGZ-ს @msg Invalid dimension offset ზომის არასწორი წანაცვლება @@ -2590,6 +2591,7 @@ Reset Retype Panel ხელახლა აკრეფის პანელის ჩამოყრა List Matching Fonts შესაბამისი შრიფტების სია Retype Preview ხელახლა აკრეფის პანელის წინასწარი ნახვა +@msg `installed` must be true, false or null `installed` უნდა იყოს true, false ან null @msg `count` must be a whole number from 1 to 96 `count` უნდა იყოს მთელი რიცხვი 1-დან 96-მდე @msg `size` must be small, medium or large `size` უნდა იყოს small, medium ან large @msg `text` must be a string of at most 100 characters `text` უნდა იყოს არაუმეტეს 100 სიმბოლოს სტრიქონი diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index 57e0b8be10..80ef7b8d34 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -514,6 +514,7 @@ digits Malayalam 말라얄람어 Reset Retype Panel 리타입 패널 재설정 List Matching Fonts 일치하는 글꼴 목록 Retype Preview 리타입 패널 미리 보기 +@msg `installed` must be true, false or null `installed`은(는) true, false 또는 null이어야 합니다 @msg `count` must be a whole number from 1 to 96 `count`는 1에서 96 사이의 정수여야 합니다 @msg `size` must be small, medium or large `size`는 small, medium 또는 large여야 합니다 @msg `text` must be a string of at most 100 characters `text`는 최대 100자의 문자열이어야 합니다 @@ -8577,6 +8578,7 @@ breakText Glyphs 글리프 @msg Image Trace failed: internal error: its thread stopped (please report this bug) 이미지 추적 실패: 내부 오류: 스레드가 멈췄습니다(이 버그를 보고해 주세요) @msg Image Trace failed: {e} 이미지 추적 실패: {e} @msg Image Trace finished, but its document was closed 이미지 추적이 끝났지만 문서가 닫혔습니다 +@msg Retype finished, but the document or its selection changed meanwhile: run it again 리타입이 끝났지만 그 사이에 문서나 선택 영역이 바뀌었습니다: 다시 실행하세요 @msg Image Trace finished, but the image or its settings changed meanwhile: trace it again 이미지 추적이 끝났지만 그 사이에 이미지나 설정이 바뀌었습니다: 다시 추적하세요 @msg Image Trace finished, but its document was reverted: trace it again 이미지 추적이 끝났지만 문서가 되돌려졌습니다: 다시 추적하세요 @msg Import SVG Filter reads SVG files, not SVGZ SVG 필터 가져오기는 SVGZ가 아닌 SVG 파일을 읽습니다 diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index 5ed5cdc3e0..e2e87b02dc 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -1045,6 +1045,7 @@ liquify-list-end {0}, {1} {0} en {1} Reset Retype Panel Paneel Opnieuw typen herstellen List Matching Fonts Overeenkomende lettertypen weergeven Retype Preview Voorbeeld in paneel Opnieuw typen +@msg `installed` must be true, false or null `installed` moet true, false of null zijn @msg `count` must be a whole number from 1 to 96 `count` moet een geheel getal van 1 tot 96 zijn @msg `size` must be small, medium or large `size` moet small, medium of large zijn @msg `text` must be a string of at most 100 characters `text` moet een tekenreeks van hoogstens 100 tekens zijn @@ -6444,6 +6445,7 @@ imageTrace Outline Contour @msg Image Trace failed: internal error: its thread stopped (please report this bug) Afbeelding traceren is mislukt: interne fout: de thread ervan is gestopt (meld deze bug alsjeblieft) @msg Image Trace failed: {e} Afbeelding traceren is mislukt: {e} @msg Image Trace finished, but its document was closed Afbeelding traceren is voltooid, maar het document ervan is gesloten +@msg Retype finished, but the document or its selection changed meanwhile: run it again Opnieuw typen is voltooid, maar het document of de selectie ervan is intussen gewijzigd: voer het opnieuw uit @msg Image Trace finished, but the image or its settings changed meanwhile: trace it again Afbeelding traceren is voltooid, maar de afbeelding of de instellingen ervan zijn intussen gewijzigd: traceer de afbeelding opnieuw @msg Image Trace finished, but its document was reverted: trace it again Afbeelding traceren is voltooid, maar het document ervan is teruggezet: traceer de afbeelding opnieuw @msg Import SVG Filter reads SVG files, not SVGZ SVG-filter importeren leest SVG-bestanden, geen SVGZ diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index 74029133dc..889f0f3ef3 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -419,6 +419,7 @@ Reset Retype Panel Resetuj panel Przepisz List Matching Fonts Wyświetl pasujące czcionki Retype Preview Podgląd w panelu Przepisz +@msg `installed` must be true, false or null `installed` musi mieć wartość true, false lub null @msg `count` must be a whole number from 1 to 96 `count` musi być liczbą całkowitą od 1 do 96 @msg `size` must be small, medium or large `size` musi mieć wartość small, medium lub large @msg `text` must be a string of at most 100 characters `text` musi być ciągiem o długości co najwyżej 100 znaków @@ -9085,6 +9086,7 @@ breakText Glyphs Glify @msg Image Trace failed: internal error: its thread stopped (please report this bug) Obrys obrazu nie powiódł się: błąd wewnętrzny: jego wątek został zatrzymany (zgłoś ten błąd) @msg Image Trace failed: {e} Obrys obrazu nie powiódł się: {e} @msg Image Trace finished, but its document was closed Obrys obrazu został ukończony, ale jego dokument został zamknięty +@msg Retype finished, but the document or its selection changed meanwhile: run it again Przepisywanie zostało ukończone, ale dokument lub jego zaznaczenie zmieniły się w międzyczasie: uruchom je ponownie @msg Image Trace finished, but the image or its settings changed meanwhile: trace it again Obrys obrazu został ukończony, ale obraz lub jego ustawienia zmieniły się w międzyczasie: obrysuj go ponownie @msg Image Trace finished, but its document was reverted: trace it again Obrys obrazu został ukończony, ale jego dokument został przywrócony: obrysuj go ponownie @msg Join: a subpath went missing Połącz: brakuje ścieżki podrzędnej diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index a1747af0b2..a59bd7944a 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -1276,6 +1276,7 @@ antiAlias Sharp Nítido Reset Retype Panel Redefinir Painel Redigitar List Matching Fonts Listar Fontes Correspondentes Retype Preview Visualização do Painel Redigitar +@msg `installed` must be true, false or null `installed` deve ser true, false ou null @msg `count` must be a whole number from 1 to 96 `count` deve ser um número inteiro de 1 a 96 @msg `size` must be small, medium or large `size` deve ser small, medium ou large @msg `text` must be a string of at most 100 characters `text` deve ser uma string de no máximo 100 caracteres @@ -8991,6 +8992,7 @@ swatch Yellow Green Verde-amarelado @msg Image Trace failed: internal error: its thread stopped (please report this bug) O Rastreamento de Imagem falhou: erro interno: a thread dele parou (informe este erro) @msg Image Trace failed: {e} O Rastreamento de Imagem falhou: {e} @msg Image Trace finished, but its document was closed O Rastreamento de Imagem terminou, mas o documento dele foi fechado +@msg Retype finished, but the document or its selection changed meanwhile: run it again O Redigitar terminou, mas o documento ou a seleção dele mudou nesse meio-tempo: execute-o novamente @msg Image Trace finished, but the image or its settings changed meanwhile: trace it again O Rastreamento de Imagem terminou, mas a imagem ou as configurações dela mudaram nesse meio-tempo: rastreie-a novamente @msg Image Trace finished, but its document was reverted: trace it again O Rastreamento de Imagem terminou, mas o documento dele foi revertido: rastreie-a novamente @msg Import SVG Filter reads SVG files, not SVGZ Importar Filtro SVG lê arquivos SVG, não SVGZ diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index ca0c8d5145..cdfc4c38ca 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -1405,6 +1405,7 @@ font-technology Variable Вариативные Reset Retype Panel Сбросить панель «Перенабор» List Matching Fonts Список подходящих шрифтов Retype Preview Просмотр в панели «Перенабор» +@msg `installed` must be true, false or null `installed` должно быть true, false или null @msg `count` must be a whole number from 1 to 96 `count` должно быть целым числом от 1 до 96 @msg `size` must be small, medium or large `size` должно быть small, medium или large @msg `text` must be a string of at most 100 characters `text` должно быть строкой длиной не более 100 символов @@ -8926,6 +8927,7 @@ shape Open Открытый @msg Image Trace failed: internal error: its thread stopped (please report this bug) Трассировка изображения не выполнена: внутренняя ошибка: её поток остановился (сообщите об этой ошибке) @msg Image Trace failed: {e} Трассировка изображения не выполнена: {e} @msg Image Trace finished, but its document was closed Трассировка изображения завершена, но её документ был закрыт +@msg Retype finished, but the document or its selection changed meanwhile: run it again Перенабор завершён, но документ или его выделение за это время изменились: выполните его снова @msg Image Trace finished, but the image or its settings changed meanwhile: trace it again Трассировка изображения завершена, но изображение или его настройки за это время изменились: выполните трассировку снова @msg Import SVG Filter reads SVG files, not SVGZ Импорт фильтра SVG читает файлы SVG, а не SVGZ @msg Invalid dimension offset Недопустимое смещение размера diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index c26474cf93..45d255129a 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -1361,6 +1361,7 @@ font-technology Variable Variabla Reset Retype Panel Återställ panelen Skriv om List Matching Fonts Lista matchande typsnitt Retype Preview Förhandsgranskning i panelen Skriv om +@msg `installed` must be true, false or null `installed` måste vara true, false eller null @msg `count` must be a whole number from 1 to 96 `count` måste vara ett heltal från 1 till 96 @msg `size` must be small, medium or large `size` måste vara small, medium eller large @msg `text` must be a string of at most 100 characters `text` måste vara en sträng på högst 100 tecken @@ -9368,6 +9369,7 @@ digits Hindi Hindi @msg Image Trace failed: {e} Bildkalkering misslyckades: {e} @msg Image Trace failed: internal error: its thread stopped (please report this bug) Bildkalkering misslyckades: internt fel: dess tråd stoppades (rapportera gärna felet) @msg Image Trace finished, but its document was closed Bildkalkeringen är klar, men dess dokument har stängts +@msg Retype finished, but the document or its selection changed meanwhile: run it again Skriv om är klar, men dokumentet eller dess markering ändrades under tiden: kör det igen @msg Image Trace finished, but the image or its settings changed meanwhile: trace it again Bildkalkeringen är klar, men bilden eller dess inställningar ändrades under tiden: vektorisera den igen @msg Image Trace finished, but its document was reverted: trace it again Bildkalkeringen är klar, men dess dokument har återgått till sparad version: vektorisera den igen @msg imageMap `{m}`: none, client or server imageMap `{m}`: none, client eller server diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index 82186ebcdd..57ab2aca77 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -1356,6 +1356,7 @@ font-technology Variable Değişken Reset Retype Panel Yeniden Yaz Panelini Sıfırla List Matching Fonts Eşleşen Yazı Tiplerini Listele Retype Preview Yeniden Yaz Paneli Önizlemesi +@msg `installed` must be true, false or null `installed` true, false veya null olmalıdır @msg `count` must be a whole number from 1 to 96 `count` 1 ile 96 arasında bir tam sayı olmalıdır @msg `size` must be small, medium or large `size` small, medium veya large olmalıdır @msg `text` must be a string of at most 100 characters `text` en fazla 100 karakterlik bir dize olmalıdır @@ -8073,6 +8074,7 @@ axis Y Axis Y ekseni @msg Image Trace failed: internal error: its thread stopped (please report this bug) Görüntü İzleme başarısız oldu: iç hata: iş parçacığı durdu (lütfen bu hatayı bildirin) @msg Image Trace failed: {e} Görüntü İzleme başarısız oldu: {e} @msg Image Trace finished, but its document was closed Görüntü İzleme tamamlandı, ancak belgesi kapatılmıştı +@msg Retype finished, but the document or its selection changed meanwhile: run it again Yeniden Yaz tamamlandı, ancak bu sırada belge veya seçimi değişti: yeniden çalıştırın @msg Image Trace finished, but the image or its settings changed meanwhile: trace it again Görüntü İzleme tamamlandı, ancak bu sırada görüntü veya ayarları değişti: yeniden izleyin @msg Image Trace finished, but its document was reverted: trace it again Görüntü İzleme tamamlandı, ancak belgesi geri döndürüldü: yeniden izleyin @msg Invalid dimension offset Geçersiz boyut ofseti diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index de3329ef10..6720ddfe41 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -1414,6 +1414,7 @@ font-technology Variable Варіативні Reset Retype Panel Скинути панель «Повторний набір» List Matching Fonts Список відповідних шрифтів Retype Preview Перегляд у панелі «Повторний набір» +@msg `installed` must be true, false or null `installed` має бути true, false або null @msg `count` must be a whole number from 1 to 96 `count` має бути цілим числом від 1 до 96 @msg `size` must be small, medium or large `size` має бути small, medium або large @msg `text` must be a string of at most 100 characters `text` має бути рядком довжиною не більше 100 символів @@ -8579,6 +8580,7 @@ breakText Glyphs Гліфи @msg Image Trace failed: internal error: its thread stopped (please report this bug) Трасування зображення не вдалося: внутрішня помилка: його потік зупинився (будь ласка, повідомте про цю помилку) @msg Image Trace failed: {e} Трасування зображення не вдалося: {e} @msg Image Trace finished, but its document was closed Трасування зображення завершено, але його документ закрито +@msg Retype finished, but the document or its selection changed meanwhile: run it again Повторний набір завершено, але документ або його виділення тим часом змінилися: виконайте його ще раз @msg Image Trace finished, but the image or its settings changed meanwhile: trace it again Трасування зображення завершено, але зображення або його параметри тим часом змінилися: виконайте трасування ще раз @msg Image Trace finished, but its document was reverted: trace it again Трасування зображення завершено, але його документ було повернуто до збереженої версії: виконайте трасування ще раз @msg Import SVG Filter reads SVG files, not SVGZ Імпорт фільтра SVG читає файли SVG, а не SVGZ diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index 675143a8d6..a914326a5e 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -1654,6 +1654,7 @@ digits Malayalam Malayalam Reset Retype Panel Đặt lại bảng Gõ lại List Matching Fonts Liệt kê phông khớp Retype Preview Xem trước trong bảng Gõ lại +@msg `installed` must be true, false or null `installed` phải là true, false hoặc null @msg `count` must be a whole number from 1 to 96 `count` phải là số nguyên từ 1 đến 96 @msg `size` must be small, medium or large `size` phải là small, medium hoặc large @msg `text` must be a string of at most 100 characters `text` phải là chuỗi tối đa 100 ký tự @@ -6945,6 +6946,7 @@ axis Y Axis Trục Y The plug-in is computing… Plug-in đang tính toán… Inspect Plug-in Kiểm tra plug-in Cancel Plug-in Run Hủy lần chạy plug-in +@msg Retype finished, but the document or its selection changed meanwhile: run it again Gõ lại đã chạy xong, nhưng tài liệu hoặc vùng chọn của nó đã thay đổi trong lúc đó: hãy chạy lại @msg {_1} finished, but the document or the plug-in changed meanwhile: run it again {_1} đã chạy xong, nhưng tài liệu hoặc plug-in đã thay đổi trong lúc đó: hãy chạy lại @msg Running “{name}”… Đang chạy “{name}”… @msg a live effect runs while the document is drawn, so it can't be `heavy` hiệu ứng trực tiếp chạy trong lúc tài liệu được vẽ nên không thể là `heavy` diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index 57f6a4403b..0d26776c45 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -1350,6 +1350,7 @@ antiAlias Sharp 锐利 Reset Retype Panel 重置重新键入面板 List Matching Fonts 列出匹配字体 Retype Preview 重新键入面板预览 +@msg `installed` must be true, false or null `installed` 必须是 true、false 或 null @msg `count` must be a whole number from 1 to 96 `count` 必须是 1 到 96 之间的整数 @msg `size` must be small, medium or large `size` 必须是 small、medium 或 large @msg `text` must be a string of at most 100 characters `text` 必须是不超过 100 个字符的字符串 @@ -9094,6 +9095,7 @@ breakText Glyphs 字形 @msg Image Trace failed: internal error: its thread stopped (please report this bug) 图像描摹失败:内部错误:其线程已停止 (请报告此错误) @msg Image Trace failed: {e} 图像描摹失败:{e} @msg Image Trace finished, but its document was closed 图像描摹已完成,但其文档已关闭 +@msg Retype finished, but the document or its selection changed meanwhile: run it again 重新键入已完成,但文档或其选区在此期间发生了更改:请重新运行 @msg Image Trace finished, but the image or its settings changed meanwhile: trace it again 图像描摹已完成,但图像或其设置在此期间发生了更改:请重新描摹 @msg Image Trace finished, but its document was reverted: trace it again 图像描摹已完成,但其文档已恢复:请重新描摹 @msg Invalid dimension offset 尺寸标注的偏移无效 diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index 9834c17ea6..f5ecae2fa9 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -1385,6 +1385,7 @@ font-technology Variable 可變 Reset Retype Panel 重設重新鍵入面板 List Matching Fonts 列出相符字體 Retype Preview 重新鍵入面板預覽 +@msg `installed` must be true, false or null `installed` 必須是 true、false 或 null @msg `count` must be a whole number from 1 to 96 `count` 必須是介於 1 到 96 的整數 @msg `size` must be small, medium or large `size` 必須是 small、medium 或 large @msg `text` must be a string of at most 100 characters `text` 必須是不超過 100 個字元的字串 @@ -9030,6 +9031,7 @@ breakText Glyphs 字符 @msg Image Trace failed: internal error: its thread stopped (please report this bug) 影像描圖失敗:內部錯誤:其執行緒已停止 (請回報此錯誤) @msg Image Trace failed: {e} 影像描圖失敗:{e} @msg Image Trace finished, but its document was closed 影像描圖已完成,但其文件已關閉 +@msg Retype finished, but the document or its selection changed meanwhile: run it again 重新鍵入已完成,但文件或其選取範圍在此期間已變更:請重新執行 @msg Image Trace finished, but the image or its settings changed meanwhile: trace it again 影像描圖已完成,但影像或其設定在此期間已變更:請重新描圖 @msg Image Trace finished, but its document was reverted: trace it again 影像描圖已完成,但其文件已回復:請重新描圖 @msg Invalid dimension offset 尺寸標註位移無效 diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index a50527cede..980eab9cea 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -69,6 +69,7 @@ pub mod prefs_dialog; pub mod print; pub mod recovery; pub mod render_worker; +pub mod retype_runs; pub mod screen_color; pub mod script_runs; pub mod scripts_menu; @@ -297,6 +298,8 @@ pub struct VectorcraftApp { pub placing: placing::Placing, /// Image Traces running off the UI thread ([`trace_runs`]). pub trace_runs: trace_runs::TraceRuns, + /// Retype's search of the installed fonts, off the UI thread ([`retype_runs`]). + pub retype_runs: retype_runs::RetypeRuns, /// The messages shown over the window ([`toasts`]). pub toasts: toasts::Shown, /// Data Recovery's timer and startup question ([`recovery`]). diff --git a/crates/ui-egui/src/menus/invoke.rs b/crates/ui-egui/src/menus/invoke.rs index 7186f0707d..06f8437972 100644 --- a/crates/ui-egui/src/menus/invoke.rs +++ b/crates/ui-egui/src/menus/invoke.rs @@ -216,6 +216,21 @@ pub fn invoke(app: &mut VectorcraftApp, id: &str, p: Value) { } return; } + // Retype and Find Matching Fonts read the installed fonts off the UI thread, with their + // progress; Find more font matches lists what the last search found at once, and before any + // search it is a new one. + let new_search = match p.get("more") { + None | Some(serde_json::Value::Null | serde_json::Value::Bool(false)) => true, + Some(serde_json::Value::Bool(true)) => !app.ui.retype.searched, + Some(_) => false, + }; + if id == "type.retype" || (id == "retype.find" && new_search) { + let r = if id == "type.retype" { crate::retype_runs::start(app, id, p, false) } else { crate::panels::retype::find_in_background(app, &p) }; + if let Err(e) = r { + app.status(e); + } + return; + } if let Some(r) = crate::panels::artboards::run_menu_item(app, id, &p) { if let Err(e) = r { app.status(e); diff --git a/crates/ui-egui/src/menus/run.rs b/crates/ui-egui/src/menus/run.rs index 8c2767e20b..e45a2450b1 100644 --- a/crates/ui-egui/src/menus/run.rs +++ b/crates/ui-egui/src/menus/run.rs @@ -1232,6 +1232,7 @@ fn run_ui_part13(app: &mut VectorcraftApp, id: &str, p: &Value) -> Option Ok(crate::plugin_runs::hide_all(app)), "imageTrace.cancelRuns" => Ok(crate::trace_runs::cancel_all(app)), "imageTrace.hideRuns" => Ok(crate::trace_runs::hide_all(app)), + "retype.cancelSearch" => Ok(crate::retype_runs::cancel(app)), "ui.checkScript" => crate::dialogs::script_check::command(app, p), "ui.runScript" => crate::dialogs::script_run::command(app, p), crate::scripts_menu::COMMAND => crate::scripts_menu::run(app, p), diff --git a/crates/ui-egui/src/menus/state.rs b/crates/ui-egui/src/menus/state.rs index 3fc578d754..053de01207 100644 --- a/crates/ui-egui/src/menus/state.rs +++ b/crates/ui-egui/src/menus/state.rs @@ -276,6 +276,7 @@ fn ui_enabled(app: &VectorcraftApp, id: &str) -> bool { "plugin.hideRuns" => crate::plugin_runs::any_shown(app), "imageTrace.cancelRuns" => crate::trace_runs::any_running(app), "imageTrace.hideRuns" => crate::trace_runs::any_shown(app), + "retype.cancelSearch" => crate::retype_runs::any_running(app), "file.place" | "file.export.svg" | "file.export.png" diff --git a/crates/ui-egui/src/menus/ui_commands.rs b/crates/ui-egui/src/menus/ui_commands.rs index 4602e12072..a9ea40df36 100644 --- a/crates/ui-egui/src/menus/ui_commands.rs +++ b/crates/ui-egui/src/menus/ui_commands.rs @@ -869,7 +869,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "retype.find", "Find Matching Fonts", "", - "{more?: bool} show the Retype panel and list the fonts whose glyphs match the selected outlined text, compared and ranked as type.retypeFonts does (up to 96 loaded fonts, those of the document's live type first): ten, as Find Matching Fonts does (more false, omitted or null: a new search), or with more: true the next five fonts the last search found (whatever is selected now; before any search, a first search), as Find more font matches does; the document does not change; a search with no path or compound path selected, or a more other than true, false or null, is an error and leaves the list as it was; returns what retype.list returns", + "{more?: bool, installed?: bool} show the Retype panel and list the fonts whose glyphs match the selected outlined text, compared and ranked as type.retypeFonts does (up to 96 loaded fonts, those of the document's live type first, then, unless installed is false, the installed fonts not loaded yet, which the app reads in the background, with retype.cancelSearch to stop it, when the panel's button, a menu or the command palette runs it): ten, as Find Matching Fonts does (more false, omitted or null: a new search), or with more: true the next five fonts the last search found (whatever is selected now; before any search, a first search), as Find more font matches does; the document does not change; a search with no path or compound path selected, or a more or installed other than true, false or null, is an error and leaves the list as it was; returns what retype.list returns", ), ( "retype.list", @@ -2026,6 +2026,12 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "", "{} close the progress window of the Image Traces running in the background; they go on, shown in the status bar → {hidden: n}", ), + ( + "retype.cancelSearch", + "Cancel Font Search", + "", + "{} stop the search of the installed fonts that Type › Retype or the Retype panel's Find Matching Fonts runs in the background (its progress window's Cancel): it stops before its next file, and Retype changes nothing and the list stays as it was → {cancelled: n}", + ), ( "ui.runScript", "Other Script…", diff --git a/crates/ui-egui/src/opening.rs b/crates/ui-egui/src/opening.rs index 5b4c8619ee..738b511432 100644 --- a/crates/ui-egui/src/opening.rs +++ b/crates/ui-egui/src/opening.rs @@ -56,6 +56,7 @@ pub fn long_operation_busy(app: &VectorcraftApp) -> bool { || !app.plugin_runs.running.is_empty() || !app.placing.pending.is_empty() || !app.trace_runs.running.is_empty() + || crate::retype_runs::any_running(app) } /// Does opening happen off the UI thread here? Not on wasm (no threads), in unit tests (they look diff --git a/crates/ui-egui/src/palette.rs b/crates/ui-egui/src/palette.rs index a3c5fed207..37dc4680e8 100644 --- a/crates/ui-egui/src/palette.rs +++ b/crates/ui-egui/src/palette.rs @@ -596,6 +596,7 @@ fn availability_key(app: &VectorcraftApp) -> u64 { app.session.active().map(|d| (d.path.is_some(), d.converted, d.is_dirty())).hash(&mut h); let plugins = (crate::plugin_runs::any_running(app), crate::plugin_runs::any_shown(app)); (plugins, crate::trace_runs::any_running(app), crate::trace_runs::any_shown(app)).hash(&mut h); + crate::retype_runs::any_running(app).hash(&mut h); h.finish() } diff --git a/crates/ui-egui/src/panels/retype.rs b/crates/ui-egui/src/panels/retype.rs index 02541cb65d..0066262f5a 100644 --- a/crates/ui-egui/src/panels/retype.rs +++ b/crates/ui-egui/src/panels/retype.rs @@ -2,7 +2,8 @@ //! by how many of its shapes each matches (`type.retypeFonts`), each with a sample //! (, //! ). -//! Find Matching Fonts lists ten, and Find more font matches at the end of the list five more. The +//! Find Matching Fonts lists ten, after reading the installed fonts not loaded yet off the UI +//! thread ([`crate::retype_runs`]), and Find more font matches at the end of the list five more. The //! list stays after the selection changes, so choosing a font in it sets that font on the live text //! selected then, as the font menus do. The sample field sets the text the samples show, and the //! panel menu sets their size; Reset Retype Panel clears the list. `retype.find`, `retype.list`, @@ -78,8 +79,10 @@ fn row_height(size: Size) -> f32 { pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { let mut run: Option<(&str, Value)> = None; let has_path = vectorcraft_engine::cmd::has_selected_path(&app.session).is_ok(); - if widgets::primary_button_enabled(ui, tl!("Find Matching Fonts"), has_path).clicked() { - run = Some(("retype.find", json!({}))); + if widgets::primary_button_enabled(ui, tl!("Find Matching Fonts"), has_path).clicked() + && let Err(e) = find_in_background(app, &json!({})) + { + app.status(e); } ui.add_space(4.0); let mut text = app.ui.retype.text.clone(); @@ -181,6 +184,8 @@ pub(crate) fn command(app: &mut VectorcraftApp, id: &str, p: &Value) -> Option Ok(list(&app.ui.retype)), "retype.preview" => preview(app, p), "retype.reset" => { + // A search Find Matching Fonts started does not fill the list again. + crate::retype_runs::drop_panel_search(app); let v = &mut app.ui.retype; (v.searched, v.fonts, v.rest, v.shapes, v.truncated) = (false, vec![], vec![], 0, false); Ok(list(&app.ui.retype)) @@ -203,11 +208,16 @@ fn list(v: &View) -> Value { }) } -/// `retype.find {more?}`: show the panel and list the first ten fonts matching the selected -/// outlined text, or with `more` add the next five the last search found, whatever is selected -/// now → what `retype.list` returns. The list stays as it was when the search fails. +/// `retype.find {more?, installed?}`: show the panel and list the first ten fonts matching the +/// selected outlined text (with `installed` false, the loaded fonts only), or with `more` add the +/// next five the last search found, whatever is selected now → what `retype.list` returns. The +/// list stays as it was when the search fails. fn find(app: &mut VectorcraftApp, p: &Value) -> Result { let more = crate::menus::opt_bool(p, "more")?.unwrap_or(false); + // A bad installed is an error even when no search runs. + if p.get("installed").is_some_and(|v| !v.is_null() && !v.is_boolean()) { + return Err("`installed` must be true, false or null".into()); + } if more && app.ui.retype.searched { // The panel shows first: a failure leaves the list as it was. crate::panel_docking::reveal_panel(app, ID)?; @@ -216,7 +226,34 @@ fn find(app: &mut VectorcraftApp, p: &Value) -> Result { v.fonts.extend(next); return Ok(list(&app.ui.retype)); } - let r = app.session.execute("type.retypeFonts", &json!({ "count": MAX })).map_err(|e| e.to_string())?; + // A search Find Matching Fonts started in the background does not replace this one's list. + crate::retype_runs::drop_panel_search(app); + search(app, &search_params(p)) +} + +/// Find Matching Fonts as the user asks for it (the panel's button, `retype.find` from a menu or the +/// command palette, `p` its params without `more`): the installed fonts are searched off the UI +/// thread ([`crate::retype_runs`]), then the list is filled. +pub(crate) fn find_in_background(app: &mut VectorcraftApp, p: &Value) -> Result { + // A bad more is an error here too, as `retype.find` has it. + crate::menus::opt_bool(p, "more")?; + crate::retype_runs::start(app, "type.retypeFonts", search_params(p), true) +} + +/// `type.retypeFonts`' params for a new search with `retype.find`'s params `p`. +fn search_params(p: &Value) -> Value { + let mut q = json!({ "count": MAX }); + if let Some(installed) = p.get("installed") { + q["installed"] = installed.clone(); + } + q +} + +/// Shows the panel and lists the first ten fonts `type.retypeFonts` with params `p` finds for the +/// selected outlined text → what `retype.list` returns. The list stays as it was when the search +/// fails. +pub(crate) fn search(app: &mut VectorcraftApp, p: &Value) -> Result { + let r = app.session.execute("type.retypeFonts", p).map_err(|e| e.to_string())?; crate::panel_docking::reveal_panel(app, ID)?; let mut fonts: Vec = r["fonts"] .as_array() diff --git a/crates/ui-egui/src/panels/retype/tests.rs b/crates/ui-egui/src/panels/retype/tests.rs index 49f067c0b2..2f1d286020 100644 --- a/crates/ui-egui/src/panels/retype/tests.rs +++ b/crates/ui-egui/src/panels/retype/tests.rs @@ -83,7 +83,8 @@ fn more_adds_fonts_until_none_is_left() { let mut app = app(); let g = outlined(&mut app, json!({"x": 40, "y": 100, "text": "More", "size": 30})); select(&mut app, &[g]); - let first = app.run("retype.find", json!({})).unwrap(); + // The installed fonts are left out, so the searches compare the same fonts. + let first = app.run("retype.find", json!({"installed": false})).unwrap(); // How many fonts match depends on the fonts loaded: ask until none is left. let mut last = first.clone(); for _ in 0..20 { @@ -100,10 +101,16 @@ fn more_adds_fonts_until_none_is_left() { // A null more is omitted: a new search lists the first ten again. A font added to the list // tells the new search apart from adding more when ten or fewer fonts match. app.ui.retype.fonts.push(super::Found { family: "Not Found".into(), style: "Regular".into(), matched: 0 }); - assert_eq!(app.run("retype.find", json!({"more": null})).unwrap(), first); + assert_eq!(app.run("retype.find", json!({"more": null, "installed": false})).unwrap(), first); // Before any search, more is a first search. app.run("retype.reset", json!({})).unwrap(); - assert_eq!(app.run("retype.find", json!({"more": true})).unwrap(), first); + assert_eq!(app.run("retype.find", json!({"more": true, "installed": false})).unwrap(), first); + // A bad installed is the command's error, and leaves the list as it was. + for p in [json!({"installed": 1}), json!({"more": true, "installed": "yes"})] { + let e = app.run("retype.find", p.clone()).unwrap_err(); + assert!(e.contains("`installed` must be true, false or null"), "{p}: {e}"); + assert_eq!(app.run("retype.list", json!({})).unwrap(), first, "{p}"); + } assert!(app.run("retype.find", json!({"more": "yes"})).is_err()); } diff --git a/crates/ui-egui/src/retype_runs.rs b/crates/ui-egui/src/retype_runs.rs new file mode 100644 index 0000000000..a4f819fc23 --- /dev/null +++ b/crates/ui-egui/src/retype_runs.rs @@ -0,0 +1,249 @@ +//! Retype's search of the installed fonts off the UI thread. Type › Retype and the Retype panel's +//! Find Matching Fonts read installed font files that nothing has loaded yet, which can take +//! seconds. Asked for by the user, the search is prepared at once, so bad params and a selection +//! with nothing to match fail before anything runs, and runs on a thread of its own ([`start`]): +//! the status bar shows it, and after [`DELAY`] a progress window shows how many files are read, +//! with Cancel (also Esc, `retype.cancelSearch`). When it is done, the command runs with the fonts +//! it loaded, unless the document or its selection changed meanwhile: then nothing changes and the +//! status bar says to run it again. The control channel, MCP and scripts run the commands at once, +//! and so does every search on the web, in unit tests that don't set `off_the_ui_thread`, and with +//! `VECTORCRAFT_SYNC_OPEN` set ([`available`]). + +use std::sync::Arc; +use std::sync::atomic::{AtomicU64, Ordering}; +use std::sync::mpsc::{Receiver, TryRecvError, channel}; + +use serde_json::{Value, json}; +use vectorcraft_doc::cancel::{self, CancelToken, ProgressSink}; +use vectorcraft_engine::EngineError; +use vectorcraft_engine::cmd::{RetypeFound, RetypeRun}; + +use crate::VectorcraftApp; +use crate::export_progress::{self, Pressed}; + +pub use crate::export_progress::DELAY; + +/// What the status bar and the progress window say. +const LABEL: &str = "Finding matching fonts"; + +/// A search running. +pub struct Running { + id: u64, + run: RetypeRun, + /// Its Cancel. + token: CancelToken, + /// The Retype panel started it, and lists what its command finds. + from_panel: bool, + /// Files read so far and in all (0 in all until the files are listed). + steps: Arc<[AtomicU64; 2]>, + done: Receiver>, +} + +/// The search running, if any. +#[derive(Default)] +pub struct RetypeRuns { + pub running: Option, + next_id: u64, + /// Set by unit tests whose app searches off the UI thread. + pub(crate) off_the_ui_thread: bool, +} + +/// Does `app` search off the UI thread? Where documents open off it ([`crate::opening::available`]), +/// and in the unit tests that set `off_the_ui_thread`. +pub fn available(app: &VectorcraftApp) -> bool { + app.retype_runs.off_the_ui_thread || crate::opening::available() +} + +/// Runs `command` (`type.retype`, or `type.retypeFonts` for the Retype panel when `from_panel`) +/// with params `p`, searching the installed fonts on a thread of its own → `{background: true, +/// status}`. Where no thread can run it, or no installed font needs reading, at once (what the +/// command, or for the panel `retype.find`, returns). Unless its params are bad, it stops the +/// search before it. +pub fn start(app: &mut VectorcraftApp, command: &str, p: Value, from_panel: bool) -> Result { + let at_once = |app: &mut VectorcraftApp, p: Value| { + if from_panel { + let installed = p.get("installed").cloned().unwrap_or(Value::Null); + app.run("retype.find", json!({ "installed": installed })) + } else { + app.run(command, p) + } + }; + if !available(app) { + stop(app); + return at_once(app, p); + } + // Bad params and nothing to match fail here, before anything runs; the search running goes on. + let prepared = RetypeRun::prepare(&app.session, command, &p).map_err(|e| e.to_string())?; + // The search before this one stops, so it cannot finish after this request. + stop(app); + let Some(run) = prepared else { + return at_once(app, p); + }; + let (tx, done) = channel(); + let token = CancelToken::new(); + let scoped = token.clone(); + let steps = Arc::new([AtomicU64::new(0), AtomicU64::new(0)]); + let counts = Arc::clone(&steps); + let search = run.search(); + std::thread::Builder::new() + .name("vectorcraft-retype".into()) + .spawn(move || { + let sink: ProgressSink = std::rc::Rc::new(move |done, total, _| { + let [done_now, total_now] = &*counts; + done_now.store(done, Ordering::Relaxed); + total_now.store(total, Ordering::Relaxed); + }); + let r = vectorcraft_engine::guard::catch_panic(|| cancel::scope(&scoped, Some(sink), || search.run())) + .map_err(|msg| format!("internal error: {msg} (please report this bug)")) + .and_then(|r| r.map_err(|e| e.to_string())); + // The app may have quit meanwhile: nothing to hand it to. + let _ = tx.send(r); + }) + .map_err(|e| e.to_string())?; + let runs = &mut app.retype_runs; + runs.next_id += 1; + runs.running = Some(Running { id: runs.next_id, run, token, from_panel, steps, done }); + if let Some(ctx) = &app.ui_ctx { + ctx.request_repaint(); + } + let status = format!("{}…", crate::i18n::msg(LABEL)); + app.status(status.clone()); + Ok(json!({ "background": true, "status": status })) +} + +/// Stops the search running, if any, without a word. +fn stop(app: &mut VectorcraftApp) { + if let Some(r) = app.retype_runs.running.take() { + r.token.cancel(); + if app.ui.status == format!("{}…", crate::i18n::msg(LABEL)) { + app.ui.status.clear(); + } + } +} + +/// Runs the command of the search that is done (each frame). Not while a dialog is open, nor while +/// an interaction is open or a tool drags with the pointer button held, as [`crate::trace_runs::poll`]. +pub fn poll(app: &mut VectorcraftApp) { + if app.ui.dialog.is_some() || app.session.in_interaction() || (app.session.tool_busy() && app.session.pointer_held()) { + return; + } + let Some(r) = &app.retype_runs.running else { return }; + let done = match r.done.try_recv() { + Ok(done) => Some(done), + Err(TryRecvError::Empty) => return, + Err(TryRecvError::Disconnected) => None, + }; + let Some(r) = app.retype_runs.running.take() else { return }; + if app.ui.status == format!("{}…", crate::i18n::msg(LABEL)) { + app.ui.status.clear(); + } + finish(app, r, done); +} + +/// Waits for the search running, then does what [`poll`] does once it is done. +#[cfg(test)] +pub(crate) fn wait(app: &mut VectorcraftApp) { + let Some(r) = app.retype_runs.running.take() else { return }; + let done = r.done.recv().ok(); + if app.ui.status == format!("{}…", crate::i18n::msg(LABEL)) { + app.ui.status.clear(); + } + finish(app, r, done); +} + +/// Runs search `r`'s command with the fonts it loaded, while its document and selection are as +/// they were; else why not, in the status bar. +fn finish(app: &mut VectorcraftApp, r: Running, done: Option>) { + // Cancel changes nothing, even when the search ended just before it. + if r.token.is_cancelled() { + app.status(EngineError::Cancelled.to_string()); + return; + } + let found = match done { + Some(Ok(found)) => found, + Some(Err(e)) => { + app.status(e); + return; + } + None => { + app.status("Retype failed: internal error: its thread stopped (please report this bug)"); + return; + } + }; + if !r.run.current(&app.session) { + app.status("Retype finished, but the document or its selection changed meanwhile: run it again"); + return; + } + // The command compares the faces found without reading the installed fonts again. + found.hand_in(&mut app.session); + let result = if r.from_panel { crate::panels::retype::search(app, r.run.params()) } else { app.run(r.run.command(), r.run.params().clone()) }; + if let Err(e) = result { + app.status(e); + } +} + +/// The progress window's Cancel (also Esc): the search stops before its next file and changes +/// nothing → `{cancelled: n}`. +pub fn cancel(app: &mut VectorcraftApp) -> Value { + let n = app.retype_runs.running.as_ref().filter(|r| !r.token.is_cancelled()).map_or(0, |r| { + r.token.cancel(); + 1 + }); + json!({ "cancelled": n }) +} + +/// Stops the Retype panel's search running, without a word: Reset Retype Panel clears the list +/// the search would fill, and a search `retype.find` runs at once fills it. +pub fn drop_panel_search(app: &mut VectorcraftApp) { + if app.retype_runs.running.as_ref().is_some_and(|r| r.from_panel) + && let Some(r) = app.retype_runs.running.take() + { + r.token.cancel(); + if app.ui.status == format!("{}…", crate::i18n::msg(LABEL)) { + app.ui.status.clear(); + } + } +} + +/// Is a search running that hasn't been canceled? +pub fn any_running(app: &VectorcraftApp) -> bool { + app.retype_runs.running.as_ref().is_some_and(|r| !r.token.is_cancelled()) +} + +/// The progress window of the search running, once it has run for [`DELAY`]. Not while a dialog +/// or another progress window is open: never two modals at once. +pub fn show(app: &mut VectorcraftApp, ctx: &egui::Context) { + let Some(r) = app.retype_runs.running.as_ref().filter(|r| !r.token.is_cancelled()) else { return }; + let now = ctx.input(|i| i.time); + let since = ctx.data_mut(|m| { + let seen = m.get_temp_mut_or_insert_with(egui::Id::unique("retype-run-seen"), || (r.id, now)); + if seen.0 != r.id { + *seen = (r.id, now); + } + seen.1 + }); + let exporting = app.background.jobs.iter().any(|j| j.progress.is_some() && !j.hidden && !j.cancelled()); + let other = exporting + || crate::plugin_runs::any_shown(app) + || crate::trace_runs::any_shown(app) + || crate::opening::any_shown(app) + || crate::placing::any_shown(app); + if now - since < DELAY || app.ui.dialog.is_some() || other { + return; + } + let [done, total] = &*r.steps; + let (done, total) = (done.load(Ordering::Relaxed), total.load(Ordering::Relaxed)); + let heading = format!("{}…", crate::i18n::msg(LABEL)); + let pressed = export_progress::window_cancel(ctx, "retype-run-progress", &heading, |ui| { + if total > 0 { + export_progress::share(ui, tl!("Reading the installed fonts…"), done.min(total) as f32 / total as f32); + } else { + export_progress::busy(ui, tl!("Reading the installed fonts…")); + } + }); + if pressed == Some(Pressed::Cancel) + && let Err(e) = app.run("retype.cancelSearch", json!({})) + { + app.status(e); + } +} diff --git a/crates/ui-egui/src/tests.rs b/crates/ui-egui/src/tests.rs index e0619ddaf7..d88dd4722e 100644 --- a/crates/ui-egui/src/tests.rs +++ b/crates/ui-egui/src/tests.rs @@ -34,6 +34,7 @@ mod quickpenbar; mod recolor; mod recovery; pub(super) mod removeanchors; +mod retype_runs; mod rotateview; mod ruler_origin; mod save; diff --git a/crates/ui-egui/src/tests/retype_runs.rs b/crates/ui-egui/src/tests/retype_runs.rs new file mode 100644 index 0000000000..19fbf1781c --- /dev/null +++ b/crates/ui-egui/src/tests/retype_runs.rs @@ -0,0 +1,191 @@ +//! Retype in the app ([`crate::retype_runs`]): Type › Retype and the Retype panel's Find Matching +//! Fonts search the installed fonts off the UI thread, then run their command, unless the document +//! or its selection changed meanwhile; Cancel stops the search and changes nothing. + +use serde_json::json; +use vectorcraft_engine::{EngineError, Session}; + +use crate::{VectorcraftApp, retype_runs}; + +/// An app whose searches run off the UI thread, with "Retype me" set in Source Sans 3, outlined and +/// selected → the app and the outlines' group. +fn outlined() -> (VectorcraftApp, u64) { + crate::i18n::set_current(crate::i18n::Lang::EN); + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.session.execute("file.new", &json!({"width": 600, "height": 400})).unwrap(); + let id = app.session.execute("text.create", &json!({"x": 40, "y": 100, "text": "Retype me", "size": 30, "font": "Source Sans 3"})).unwrap()["id"] + .as_u64() + .unwrap(); + app.session.execute("select.set", &json!({"ids": [id]})).unwrap(); + let g = app.session.execute("type.createOutlines", &json!({})).unwrap()["ids"][0].as_u64().unwrap(); + app.session.execute("select.set", &json!({"ids": [g]})).unwrap(); + app.retype_runs.off_the_ui_thread = true; + (app, g) +} + +fn undos(app: &VectorcraftApp) -> usize { + app.session.doc().unwrap().history.undo.len() +} + +fn has_type(app: &VectorcraftApp) -> bool { + let mut found = false; + app.session.doc().unwrap().doc.walk(|n| found |= matches!(n.kind, vectorcraft_doc::NodeKind::Text(_))); + found +} + +#[test] +fn type_retype_searches_off_the_ui_thread_then_retypes_as_one_undo_step() { + let (mut app, _) = outlined(); + let before = undos(&app); + crate::menus::invoke(&mut app, "type.retype", json!({})); + assert!(app.retype_runs.running.is_some(), "the search runs in the background"); + assert_eq!(app.ui.status, "Finding matching fonts…"); + assert_eq!(undos(&app), before, "nothing yet"); + retype_runs::wait(&mut app); + assert!(app.retype_runs.running.is_none()); + assert_eq!(undos(&app), before + 1, "one undo step: {}", app.ui.status); + assert!(has_type(&app), "the outlines are type again"); +} + +/// Starting a search asks for a frame, so its result is picked up without input. +#[test] +fn starting_a_search_asks_for_a_frame() { + let (mut app, _) = outlined(); + let ctx = egui::Context::default(); + app.adopt_context(&ctx); + for _ in 0..5 { + if !ctx.has_requested_repaint() { + break; + } + let mut out = ctx.run_ui(Default::default(), |_| {}); + out.textures_delta.clear(); + } + assert!(!ctx.has_requested_repaint(), "the context settled"); + crate::menus::invoke(&mut app, "type.retype", json!({})); + assert!(app.retype_runs.running.is_some()); + assert!(ctx.has_requested_repaint()); + retype_runs::wait(&mut app); +} + +#[test] +fn cancel_changes_nothing() { + let (mut app, _) = outlined(); + let before = undos(&app); + crate::menus::invoke(&mut app, "type.retype", json!({})); + assert_eq!(app.run("retype.cancelSearch", json!({})).unwrap(), json!({"cancelled": 1})); + assert_eq!(app.run("retype.cancelSearch", json!({})).unwrap(), json!({"cancelled": 0}), "already canceled"); + retype_runs::wait(&mut app); + assert_eq!(undos(&app), before, "canceled: nothing changes, even when the search ended first"); + assert!(!has_type(&app)); + assert_eq!(app.ui.status, EngineError::Cancelled.to_string()); +} + +#[test] +fn a_search_whose_selection_changed_meanwhile_changes_nothing() { + let (mut app, g) = outlined(); + let before = undos(&app); + crate::menus::invoke(&mut app, "type.retype", json!({})); + app.session.execute("select.set", &json!({"ids": []})).unwrap(); + app.session.execute("select.set", &json!({"ids": [g]})).unwrap(); + // The same objects selected again: it still applies. + retype_runs::wait(&mut app); + assert_eq!(undos(&app), before + 1); + // Another selection when it is done: nothing changes. + app.run("edit.undo", json!({})).unwrap(); + app.session.execute("select.set", &json!({"ids": [g]})).unwrap(); + let before = undos(&app); + crate::menus::invoke(&mut app, "type.retype", json!({})); + app.session.execute("select.set", &json!({"ids": []})).unwrap(); + retype_runs::wait(&mut app); + assert_eq!(undos(&app), before); + assert_eq!(app.ui.status, "Retype finished, but the document or its selection changed meanwhile: run it again"); +} + +#[test] +fn find_matching_fonts_lists_the_fonts_once_the_search_is_done() { + let (mut app, _) = outlined(); + let r = retype_runs::start(&mut app, "type.retypeFonts", json!({"count": 96}), true).unwrap(); + assert_eq!(r["background"], json!(true), "{r}"); + assert!(!app.ui.retype.searched, "nothing listed yet"); + retype_runs::wait(&mut app); + assert!(app.ui.retype.searched); + // Other tests load renamed copies of the bundled fonts, which tie with it: it may be among the + // fonts Find more font matches adds. + let v = &app.ui.retype; + assert!(!v.fonts.is_empty()); + assert!(v.fonts.iter().chain(&v.rest).any(|f| f.family == "Source Sans 3"), "{:?} {:?}", v.fonts, v.rest); + assert!(crate::panel_docking::showing(&app.ui, crate::panels::retype::ID), "the panel shows"); + // From a menu or the command palette, retype.find searches in the background too; with the + // installed fonts left out it lists at once. + app.run("retype.reset", json!({})).unwrap(); + crate::menus::invoke(&mut app, "retype.find", json!({})); + assert!(app.retype_runs.running.is_some() && !app.ui.retype.searched); + retype_runs::wait(&mut app); + assert!(app.ui.retype.searched); + // Find more font matches before any search is a first search, in the background too. + app.run("retype.reset", json!({})).unwrap(); + crate::menus::invoke(&mut app, "retype.find", json!({"more": true})); + assert!(app.retype_runs.running.is_some() && !app.ui.retype.searched); + retype_runs::wait(&mut app); + assert!(app.ui.retype.searched); + // After a search it adds to the list at once. + crate::menus::invoke(&mut app, "retype.find", json!({"more": true})); + assert!(app.retype_runs.running.is_none()); + app.run("retype.reset", json!({})).unwrap(); + crate::menus::invoke(&mut app, "retype.find", json!({"installed": false})); + assert!(app.retype_runs.running.is_none() && app.ui.retype.searched); +} + +#[test] +fn reset_retype_panel_stops_the_panel_s_search() { + let (mut app, _) = outlined(); + retype_runs::start(&mut app, "type.retypeFonts", json!({"count": 96}), true).unwrap(); + app.run("retype.reset", json!({})).unwrap(); + assert!(app.retype_runs.running.is_none(), "the search is stopped"); + retype_runs::wait(&mut app); + assert!(!app.ui.retype.searched, "the list stays cleared"); + assert!(app.ui.status.is_empty(), "{}", app.ui.status); + // A new search the command runs at once stops it too, so it does not replace the new list. + retype_runs::start(&mut app, "type.retypeFonts", json!({"count": 96}), true).unwrap(); + let listed = app.run("retype.find", json!({"installed": false})).unwrap(); + assert!(app.retype_runs.running.is_none(), "the older search is stopped"); + retype_runs::wait(&mut app); + assert_eq!(app.run("retype.list", json!({})).unwrap(), listed); + // Retype's own search goes on. + crate::menus::invoke(&mut app, "type.retype", json!({})); + app.run("retype.reset", json!({})).unwrap(); + assert!(app.retype_runs.running.is_some()); + retype_runs::wait(&mut app); +} + +#[test] +fn without_a_thread_or_with_the_installed_fonts_left_out_the_command_runs_at_once() { + let (mut app, _) = outlined(); + let r = retype_runs::start(&mut app, "type.retype", json!({"installed": false}), false).unwrap(); + assert!(r["ids"].is_array(), "the command's own result: {r}"); + assert!(app.retype_runs.running.is_none()); + let (mut app, _) = outlined(); + app.retype_runs.off_the_ui_thread = false; + let r = retype_runs::start(&mut app, "type.retypeFonts", json!({"count": 96}), true).unwrap(); + assert_eq!(r["searched"], json!(true), "what retype.find returns: {r}"); + assert!(app.retype_runs.running.is_none()); + // A request that runs at once stops the search before it, which does not apply later. + let (mut app, _) = outlined(); + let before = undos(&app); + crate::menus::invoke(&mut app, "type.retype", json!({})); + assert!(app.retype_runs.running.is_some()); + // A request with bad params leaves it running. + assert!(retype_runs::start(&mut app, "type.retype", json!({"installed": 1}), false).is_err()); + assert!(app.retype_runs.running.is_some(), "the search goes on"); + retype_runs::start(&mut app, "type.retype", json!({"installed": false}), false).unwrap(); + assert!(app.retype_runs.running.is_none(), "the older search is stopped"); + assert_eq!(undos(&app), before + 1, "the new request retyped once"); + // Bad params fail before anything runs. + let (mut app, _) = outlined(); + assert!(retype_runs::start(&mut app, "type.retype", json!({"installed": 1}), false).is_err()); + assert!(crate::panels::retype::find_in_background(&mut app, &json!({"more": "yes"})).is_err()); + assert!(crate::panels::retype::find_in_background(&mut app, &json!({"installed": "yes"})).is_err()); + crate::menus::invoke(&mut app, "retype.find", json!({"more": 1})); + assert!(app.retype_runs.running.is_none() && !app.ui.retype.searched); + assert!(app.ui.status.contains("`more` must be true or false"), "{}", app.ui.status); +} diff --git a/docs/gaps.md b/docs/gaps.md index df988ebe81..4fd6841f69 100644 --- a/docs/gaps.md +++ b/docs/gaps.md @@ -505,7 +505,7 @@ macOS cursor delivery (#2292) is narrowed to a native host adapter using the exi - **Missing:** CJK vertical composition (custom mojikumi sets and the Mojikumi Settings dialog, kinsoku settings #633, manual tate-chu-yoko), Middle Eastern features beyond bidi, digit types, Character Direction and Kashidas (a split caret; the Middle Eastern & South Asian composers are done, #4935), - Touch Type, Retype beyond exact matches of available fonts (phase 1 is in, #4934, and the Retype panel lists the exactly matching fonts; near matches, installed fonts not yet loaded and text in images remain), Snap to Glyph; optional preservation of font sizes during group scaling (#1034 enhancement). + Touch Type, Retype beyond exact matches of available fonts (phase 1 is in, #4934, and the Retype panel lists the exactly matching fonts, installed fonts not yet loaded included; near matches and text in images remain), Snap to Glyph; optional preservation of font sizes during group scaling (#1034 enhancement). Itemized in [type-parity.md](type-parity.md). - **Impact:** professional typography and Japanese/Chinese publishing. - **Estimate:** 34–47 h (type core 14–19 h blocks beta). diff --git a/docs/mcp.md b/docs/mcp.md index e7abf476a9..d93549e591 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -12577,7 +12577,7 @@ on an open path that are not drawn because they fall before the path's start can ## Retype tracking -`type.retype {fonts?}` turns selected outlined text back into point text when its shapes are glyphs of a font the app +`type.retype {fonts?, installed?}` turns selected outlined text back into point text when its shapes are glyphs of a font the app has. A line of three or more glyphs gets the spacing that most of its gaps share as its tracking, in 1/1000 em. Retype tries the value rounded to a whole number first when it is within 0.05 of one, then the value as measured. The font's advances and pair kerning are left out of the measure, and word spaces are counted after the tracking. The tracking is @@ -12618,20 +12618,54 @@ the result's `texts` list holds an object's lines joined by `\n`, and each entry ## Retype panel -`type.retypeFonts {count?}` lists the fonts whose glyphs match the selected outlined text. It compares each selected path +`type.retypeFonts {count?, installed?}` lists the fonts whose glyphs match the selected outlined text. It compares each selected path and compound path, inside groups too, with the glyphs of up to 96 loaded fonts, those of the document's live type first, by the matching `type.retype` uses, and it counts only exact matches. When two versions of a font are loaded, only the version its family and style name gives is compared, which is the version that choosing the font sets. The fonts rank by how many shapes each matches, then by the mean distance left after fitting, then by family and style name. `count` is a whole number from 1 to 96 (default 10); any other value is an error. The reply is -`{fonts: [{family, style, matched}], shapes, more, truncated}`: `matched` is the number of shapes the font matches, -`shapes` the number of shapes compared, `more` is true when more fonts match than `count`, and `truncated` is true when -shapes past the limits of `type.retype` were left out. Shapes that `type.retype` would keep as outlines because of -their paint still count. The command does not change the document and records no undo step. With no path or compound -path selected it is an error. +`{fonts: [{family, style, matched}], shapes, more, truncated, installed}`: `matched` is the number of shapes the +font matches, `shapes` the number of shapes compared, `more` is true when more fonts match than `count`, and +`truncated` is true when shapes past the limits of `type.retype` were left out. Shapes that `type.retype` would keep as +outlines because of their paint still count. The command does not change the document and records no undo step. With +no path or compound path selected it is an error. `type.retypeFonts` also compares the installed fonts that are not +loaded yet, as described under Retype installed fonts, and reads every installed file within those limits, so one +search can read up to 2 GiB; the fonts that match are loaded and ranked with the others while the list holds fewer +than 96 fonts. A matching font that is shadowed by another version of the same family and style is loaded and not +listed, and does not take a place. `installed` is `{read, skipped}` as for `type.retype`; when the list is full, the +installed faces not compared count as skipped, and `more` does not count them. -Window › Retype shows the Retype panel. Find Matching Fonts runs `retype.find {}`, which shows the panel, ranks up to -96 fonts and lists the first ten. Find more font matches, at the end of the list when `more` is true, runs +## Retype installed fonts + +`type.retype {fonts?, installed?}` compares the shapes that no loaded font, document font or font in `fonts` matches +with the installed fonts that are not loaded yet. It reads their files one at a time, smallest first, and stops when +every such shape matches a font it has read. It leaves out files larger than 256 MiB, and the files and faces past +2 GiB read or 500,000 glyphs drawn in all. A file is read for the search and then released; a font whose glyphs match +a shape is loaded from what the search read, without the family's other files. A plain shape (one contour of up to +four straight edges, such as a rectangle or a hyphen) does not start the search, and matches only a font the other +shapes found. With `installed: false` the installed fonts are not read; `installed` true, omitted or null reads them, +and any other value is an error. The result's `installed` is `{read, skipped}`: the installed faces compared, and the +faces the limits left out. These limits are VectorCraft's own. + +The fonts a search loads stay loaded for the rest of the session, also when Retype then finds nothing to set, and later +searches in every open document compare them ahead of the other loaded fonts. A request that is canceled (an MCP +cancel) stops the search between files and leaves the document as it was; the fonts loaded before the cancel stay +loaded. In the app, Type › Retype and Find Matching Fonts (the Retype panel's button, or `retype.find` run from a +menu or the command palette) search on a thread of their own: the +status bar shows "Finding matching fonts…", and a progress window with Cancel (also Esc) opens when the search takes +longer than 0.4 seconds. Cancel runs `retype.cancelSearch {}` → `{cancelled: n}`, after which Retype changes nothing +and the list stays as it was. When the search is done, Retype runs, or the panel lists the fonts, with the fonts the +search found, without reading the installed fonts again. If the document or its selection changed meanwhile, nothing changes and the status bar says to run it +again. `retype.find {installed: false}` lists the loaded fonts only. The control channel and scripts run the commands +at once. + +```json +{"name":"run_command","arguments":{"command":"type.retype","params":{"installed":false}}} +``` + +Window › Retype shows the Retype panel. Find Matching Fonts searches as `retype.find {}` does, reading the installed +fonts in the background (see Retype installed fonts); `retype.find {}` shows the panel, ranks up to 96 fonts and lists +the first ten, and `retype.find {installed: false}` compares the loaded fonts only. Find more font matches, at the end of the list when `more` is true, runs `retype.find {more: true}`, which adds the next five fonts that search found, whatever is selected now. Before any search, `retype.find {more: true}` runs a first search. With `more` false, omitted or null, `retype.find` runs a new search; any other value than true, false or null is an error. A search that fails is an error and leaves the list as @@ -12645,7 +12679,7 @@ of `type.retype` (2,048 shapes, 16 nested groups); the panel then says that some `size` is `small`, `medium` or `large`, and `text` is the samples' text (empty for a generic sample). The panel menu's Small, Medium and Large items and the sample field run `retype.preview {size?, text?}`. `text` holds at most 100 characters; any other value of either key is an error and changes nothing. Reset Retype Panel in the panel menu runs `retype.reset {}`, which clears the list and keeps the size -and text. `retype.find`, `retype.preview` and `retype.reset` return what `retype.list` returns. +and text; a search Find Matching Fonts started in the background stops and does not fill the list. `retype.find`, `retype.preview` and `retype.reset` return what `retype.list` returns. ```json {"name":"run_command","arguments":{"command":"type.retypeFonts","params":{"count":5}}} diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index b1d981428a..6118024c68 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -3070,7 +3070,7 @@ The public pages describe Retype finding the fonts that match selected outlined ## Retype panel (2026-11-18) -The identify-fonts page has the Retype panel list ten matching fonts ordered by closeness, with five more on request, previews in one of three text sizes and the user's own sample text ([identify fonts](https://helpx.adobe.com/illustrator/desktop/design-with-text/fonts-and-scripts/identify-fonts-using-retype.html)). Window › Retype shows the Retype panel. Find Matching Fonts (`retype.find`, on `type.retypeFonts`) lists the fonts whose glyphs the selected shapes exactly match, comparing up to 96 loaded fonts with those of the document's live type first, so a matching font past that limit is not listed; Find more font matches adds five. The 96-font limit is VectorCraft's own. The order is VectorCraft's own: by how many shapes each font matches, then by how closely. The sample sizes (Small, Medium, Large) and the 100-character sample text limit are VectorCraft's own too. Each row shows a sample in the font, in the size the panel menu sets and with the text typed in the panel, and a click on a row sets the font on the selected live type. Tested in `crates/engine/src/cmd/retype_fonts_tests.rs` and `crates/ui-egui/src/panels/retype/tests.rs`. Opening the panel from the Type menu, the context menu and the Properties panel's Quick Actions, filtering the list by font source and favorites, near matches, installed fonts not yet loaded and images remain. +The identify-fonts page has the Retype panel list ten matching fonts ordered by closeness, with five more on request, previews in one of three text sizes and the user's own sample text ([identify fonts](https://helpx.adobe.com/illustrator/desktop/design-with-text/fonts-and-scripts/identify-fonts-using-retype.html)). Window › Retype shows the Retype panel. Find Matching Fonts (`retype.find`, on `type.retypeFonts`) lists the fonts whose glyphs the selected shapes exactly match, comparing up to 96 loaded fonts with those of the document's live type first, so a matching font past that limit is not listed; Find more font matches adds five. The 96-font limit is VectorCraft's own. The order is VectorCraft's own: by how many shapes each font matches, then by how closely. The sample sizes (Small, Medium, Large) and the 100-character sample text limit are VectorCraft's own too. Each row shows a sample in the font, in the size the panel menu sets and with the text typed in the panel, and a click on a row sets the font on the selected live type. Tested in `crates/engine/src/cmd/retype_fonts_tests.rs` and `crates/ui-egui/src/panels/retype/tests.rs`. Opening the panel from the Type menu, the context menu and the Properties panel's Quick Actions, filtering the list by font source and favorites, near matches and images remain; installed fonts not yet loaded are compared too (see Retype installed fonts). ## Retype tracking (2026-11-19) @@ -3080,6 +3080,10 @@ The identify-fonts page has the Retype panel list ten matching fonts ordered by #4934 asks for area text when outlined text has several lines, with its line spacing. `type.retype` now turns lines that follow each other, stack at one leading and line up at their starts, ends or centers into one area type object with that leading and left, right or center alignment. These rules are VectorCraft's own. Each object is laid out and compared with the outlines before it is kept; when area type would move a glyph, the lines become multi-line point type, and when that also would, the block ends at the line of that glyph and the lines after it join again. Tested by round trips through Create Outlines (three lines with Auto leading; set leading with left, center and right alignment; long blocks at leadings finer than a thousandth of a point; a line tracked apart from the others; tracked lines with word spaces; lines far apart or askew; a shape painted between two lines; translucent, blended, gradient and stroked lines; lines under a Text Wrap object) in `crates/engine/src/cmd/retype_tests.rs`. +## Retype installed fonts (2026-11-20) + +The identify-fonts page names the fonts on the device as one of the sources Retype suggests fonts from ([identify fonts](https://helpx.adobe.com/illustrator/desktop/design-with-text/fonts-and-scripts/identify-fonts-using-retype.html)). `type.retype` now compares the shapes no loaded font matches with the installed fonts that are not loaded yet, and `type.retypeFonts` (the Retype panel's list) ranks those fonts with the loaded ones. Each file is read for the search and released, smallest first; only a font whose glyphs match a shape is loaded. The search leaves out files over 256 MiB and the files and faces past 2 GiB read or 500,000 glyphs drawn, a cancel stops it between files, a plain shape (one contour of up to four straight edges) does not start it, and `installed: false` turns it off. In the app, Type › Retype and Find Matching Fonts run the search on a thread of their own, with a progress window and Cancel (`retype.cancelSearch`), and change nothing when the document or its selection changed meanwhile. These limits and rules are VectorCraft's own. Tested with installed copies of a bundled font in a folder of their own (found and loaded, no match, plain shapes, stopping once every shape matches, the three limits, a cancel before and between files, the panel's ranking, a search made away from its command) in `crates/engine/src/cmd/retype_installed_tests.rs`, `crates/engine/src/cmd/retype_fonts_tests.rs`, `crates/text/src/fontdb/installed.rs` and `crates/text/src/retype.rs`, and in the app (the background search, Cancel, a changed selection, the panel's list) in `crates/ui-egui/src/tests/retype_runs.rs`. + ## Control bar: Paragraph section while type is selected (2026-11-06) With type selected, the Control bar shows a Paragraph: link and the Align left, Align center and Align right buttons after its Character controls, as the public documentation has the Control panel format paragraphs while the Type tool is in use, with a way to the Paragraph panel ([Paragraph panel overview](https://helpx.adobe.com/illustrator/using/formatting-paragraphs.html)), and its alignment buttons align text as the Paragraph panel's do ([Align text](https://helpx.adobe.com/illustrator/using/align-text.html)). A button aligns the selected type (`text.setStyle {justify}`, one undo step) and the shared alignment shows selected; the link opens the Paragraph panel in a popover under it, as Character: opens the Character panel. Keeping to the three alignments that don't justify is our choice, for the bar's room; the popover has all seven. Short of room the bar leaves controls out from its right end: the inline X/Y/W/H fields, the Distribute and Align buttons, area type's vertical alignment, then these buttons and last the link, keeping room for the Transform link; on a 1536 pt bar with one point type object, the buttons show (pinned by a headless test, #5372). diff --git a/docs/type-parity.md b/docs/type-parity.md index 111ee5d838..5a8d2d5651 100644 --- a/docs/type-parity.md +++ b/docs/type-parity.md @@ -56,7 +56,7 @@ against Illustrator's public documentation; **estimated** unless noted. | Alt + numeric-keypad codes while typing (Windows: `Alt+0176` → °) | partial | #5108: on Windows the character Windows posts when Alt comes up after keypad digits is typed at the caret like any other, in the typing's undo step, and the keypad digits typed with Alt run no shortcut. With NumLock off the keypad keys (Insert, End, arrows, Clear, Home, Page Up/Down without the extended-key flag) count as digits too and don't move the caret (`windows_alt_codes` unit tests; neither NumLock on nor off has been tried on a Windows machine yet). `type.insert {code}` (Windows Alt+0 code, Windows-1252 for 128–159) and `{unicode}` (hex code point) insert a character by its code (`menucmds::insert_a_character_by_its_code`). macOS and Linux have no such system convention and egui reports a keypad digit as the top-row digit, so there it does nothing; a floating panel window doesn't receive the character | | Caret: the arrows and Delete step over whole clusters (Thai consonant with its marks, combining accents, emoji); Backspace removes one character | done | in text with right-to-left characters the arrows move in visual order and stop on both sides of a character drawn with no width, such as a zero width non-joiner | | Touch Type tool | done | moves, scales and rotates one character through its kerning, baseline shift, scales and rotation (`text.touchType`); a character with a preceding logical character on the same line can move along the line in either reading direction; the first logical character moves only up and down. Positive `dx` follows reading order. These direction rules are VectorCraft's choices. | -| Retype (identify fonts in outlines/images) | partial | Phase 1 (#4934): Type › Retype (`type.retype`) turns outlined glyphs back into type when each shape is exactly a glyph of a loaded font, a font the document uses or a family named in `fonts` (the same up to uniform scale, rotation and translation): one object per line unless lines stack into one object as described below, in that font and size, at the same baseline and turn, with the first glyph's fill and stroke, in one undo step; shapes that match no font stay as they are and are reported. Evenly spaced glyphs keep their spacing as tracking (gaps one space wide stay word spaces when type draws them), and lines stacked at one leading and lined up at their starts, ends or centers become one area type object with that leading and alignment (VectorCraft's own rules, checked against the layout). Window › Retype shows the Retype panel, which lists the fonts whose glyphs exactly match at least one selected outlined shape, comparing up to 96 loaded fonts with those of the document's live type first, ranked by how many shapes each matches, with samples, and sets a listed font on selected live type (`retype.find`, `type.retypeFonts`). Missing (phase 2): near or fuzzy matches (another version of the font, simplified outlines, glyphs merged into one path), opening the panel from the Type menu, the context menu and the Properties panel's Quick Actions, filtering the list by font source and favorites, installed fonts not yet loaded, text in images. Public behaviour: [identify fonts](https://helpx.adobe.com/illustrator/desktop/design-with-text/fonts-and-scripts/identify-fonts-using-retype.html), [apply to live text](https://helpx.adobe.com/illustrator/desktop/design-with-text/fonts-and-scripts/apply-retype-suggested-fonts-to-live-text.html) | +| Retype (identify fonts in outlines/images) | partial | Phase 1 (#4934): Type › Retype (`type.retype`) turns outlined glyphs back into type when each shape is exactly a glyph of a loaded font, a font the document uses or a family named in `fonts` (the same up to uniform scale, rotation and translation): one object per line unless lines stack into one object as described below, in that font and size, at the same baseline and turn, with the first glyph's fill and stroke, in one undo step; shapes that match no font stay as they are and are reported. Evenly spaced glyphs keep their spacing as tracking (gaps one space wide stay word spaces when type draws them), and lines stacked at one leading and lined up at their starts, ends or centers become one area type object with that leading and alignment (VectorCraft's own rules, checked against the layout). Window › Retype shows the Retype panel, which lists the fonts whose glyphs exactly match at least one selected outlined shape, comparing up to 96 loaded fonts with those of the document's live type first, ranked by how many shapes each matches, with samples, and sets a listed font on selected live type (`retype.find`, `type.retypeFonts`). Both also compare the installed fonts not loaded yet, reading their files within VectorCraft's own limits (256 MiB per file, 2 GiB and 500,000 glyphs per search) and loading only the fonts that match; in the app the search runs in the background with Cancel (`retype.cancelSearch`). Missing (phase 2): near or fuzzy matches (another version of the font, simplified outlines, glyphs merged into one path), opening the panel from the Type menu, the context menu and the Properties panel's Quick Actions, filtering the list by font source and favorites, text in images. Public behaviour: [identify fonts](https://helpx.adobe.com/illustrator/desktop/design-with-text/fonts-and-scripts/identify-fonts-using-retype.html), [apply to live text](https://helpx.adobe.com/illustrator/desktop/design-with-text/fonts-and-scripts/apply-retype-suggested-fonts-to-live-text.html) | | Snap to Glyph | done | View › Snap to Glyph (`view.snapToGlyph`): with Smart Guides on, new point type and drawing tools snap to live-text baselines and glyph bounds, the corners of each glyph's box included, turning with rotated type (#5112; `guides::tests::a_drawn_point_lands_on_a_corner_of_a_glyphs_bounds`, `Targets::for_drawing`, `tools::text_tests::snap_to_glyph_lines_up_new_point_type_with_a_baseline`). With Alignment Guides on as well, and Snap to Grid and Snap to Pixel off, both ends of a Measure or Measure & Inspect drag snap to those guides and show them during the drag (`Targets::for_measure`, `xform::measure::tests::its_ends_land_on_glyph_guides_with_snap_to_glyph`). That the Measure tools take the guides is VectorCraft's choice; they leave out Anchor Point, which [the help page](https://helpx.adobe.com/illustrator/desktop/design-with-text/special-characters-glyphs/snap-to-glyph.html) limits to the Pen tool and objects moved with the Selection tool. Character panel menu › Show Snap to Glyph Options: Baseline, x-height, Glyph Bounds, Proximity Guides, Angular Guides and Anchor Point each turn their guides on or off (`view.snapToGlyph.options`, all on by default; #4232), after a Snap to Glyph checkbox for View › Snap to Glyph; showing them scrolls the panel to them (#5273) | | Thai, Lao, Khmer, Myanmar: shaping (marks, reordering), lines broken between words, word-by-word caret and double-click | done | words found by ICU4X's line segmenter: dictionaries on the desktop, LSTM models on the web | | Middle Eastern: bidirectional layout, Paragraph Direction | done | PDF export keeps harakat and zero-advance Noto Arabic dot glyphs in one compatible batch per layout line, with per-glyph vertical offsets (#6309). `crates/pdf/src/tests/realtext.rs` (`mark_text_*`) checks decoded cluster mappings, mixed Arabic/Latin/digits, contour placement against outline export, vertical columns, differing path rotations and PDF/X-1a/3/4. Editable-text import still needs ActualText support (#6165); separately styled or differently rotated clusters and external viewer search/copy remain outside this export-only evidence. | diff --git a/docs/ui-parity.md b/docs/ui-parity.md index 911f08d192..47a1ef4f85 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -513,7 +513,7 @@ next unit in the order a right-click on a ruler lists them, from Feet back to Po | Swatches item context menu (G12) | done | List and thumbnail items offer Swatch Options…, Duplicate Swatch and Delete Swatch for the clicked item. Right-click selects without applying paint; reserved/missing items disable actions. All 39 Swatches tests pass, including all five views and Undo; the regression fails with the menu hooks removed. Rendered headless menus inspected. Full workspace CI passed on Linux/WSL on the merged branch (all 13 gates), including the test-helper correction for the upstream compile error tracked in #7727; native Windows full CI has two unchanged engine-test failures. | | Links panel row context menu (G12) | done | Right-clicking a link row presents an item context menu offering Relink…, Go To Link, Update Link, Edit Original, Show in Folder, and Embed Image / Unembed…; right-clicking an unselected row selects it first, preserving selection if already part of a multi-selection. Tests: `panels::tests_links::right_click_context_menu_in_links_panel`. | | SVG Interactivity panel: JavaScript for each object's events and the document's linked JavaScript files, written to SVG and read back as text | done | `svgInteractivity.*`, `ui.javascriptFilesDialog` | -| Retype panel | partial | Window › Retype lists the fonts whose glyphs exactly match at least one selected outlined shape, ranked by how many shapes each matches, ten and then five more, with samples in three sizes and the user's own text; a click sets the font on selected live type (`retype.find`, `type.retypeFonts`). Opening it from the Type menu, the context menu and the Properties panel, filtering by font source and favorites, near matches, installed fonts not yet loaded and text in images are missing (#4934) | +| Retype panel | partial | Window › Retype lists the fonts whose glyphs exactly match at least one selected outlined shape, ranked by how many shapes each matches, ten and then five more, with samples in three sizes and the user's own text; a click sets the font on selected live type (`retype.find`, `type.retypeFonts`). Installed fonts not loaded yet are compared too, read in the background with Cancel (`retype.cancelSearch`). Opening it from the Type menu, the context menu and the Properties panel, filtering by font source and favorites, near matches and text in images are missing (#4934) | | Comments, Version History panels | missing | cloud features (out of scope) | | Blend panel (30.7) | partial | Window › Blend provides Type (Ease In, Ease Out, Ease In Out, Ease Out In), Ramp 0–100% and independent color Shift, alongside the existing blend controls. Easing is disabled without a spine. Original polynomial distributions approximate the publicly documented behavior. On-canvas Appearance and Easing widgets set Shift and Ramp; a blend without a spine shows the Appearance widget alone. [Public source](https://helpx.adobe.com/illustrator/desktop/manage-colors/apply-transparency-and-blending/blend-panel-overview.html) | | Gradient panel: Dither (30.0) | done | Dither box under the stops (`paint.editGradient` `dither`); dimmed behind the Stroke proxy, fills only; `panels::gradient` test | From 5200e3c54b306b9e88a29f13de52d65516e7f4de Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 20 Nov 2026 01:11:02 -0800 Subject: [PATCH 012/151] Retype: loaded fonts past the first 96 are compared too Retype compares at most 96 loaded faces in one index: the document's fonts, the fonts in `fonts` and the faces earlier searches of the installed fonts loaded come first. Loaded faces past those 96 were never compared, and the search of the installed fonts leaves loaded faces out, so a shape only such a face matches stayed unmatched. - type.retype now compares the loaded faces past the first 96, 96 at a time, with the shapes that are not plain and that the first 96 do not match, before it reads any installed file. The background search hands those faces to the command with what it found in the installed fonts. - A face that another version of its family and style shadows is no longer compared ahead of the other loaded faces. - A background search whose command fails before it takes what the search found no longer leaves it for a later command. - With the Retype panel's list full, installed faces count as skipped only when a shape would start a search of the installed fonts. - "Retype failed: internal error: its thread stopped" has a row in each complete catalog. Docs: docs/mcp.md (Retype installed fonts). --- crates/engine/src/cmd/retype.rs | 59 ++++++++---- crates/engine/src/cmd/retype_fonts.rs | 5 +- crates/engine/src/cmd/retype_installed.rs | 80 +++++++++++++++-- .../engine/src/cmd/retype_installed_tests.rs | 90 +++++++++++++++++++ crates/ui-egui/src/i18n/ca.tsv | 1 + crates/ui-egui/src/i18n/cs.tsv | 1 + crates/ui-egui/src/i18n/da.tsv | 1 + crates/ui-egui/src/i18n/de.tsv | 1 + crates/ui-egui/src/i18n/el.tsv | 1 + crates/ui-egui/src/i18n/es.tsv | 1 + crates/ui-egui/src/i18n/fi.tsv | 1 + crates/ui-egui/src/i18n/fr.tsv | 1 + crates/ui-egui/src/i18n/hi.tsv | 1 + crates/ui-egui/src/i18n/hu.tsv | 1 + crates/ui-egui/src/i18n/id.tsv | 1 + crates/ui-egui/src/i18n/it.tsv | 1 + crates/ui-egui/src/i18n/ja.tsv | 1 + crates/ui-egui/src/i18n/ka.tsv | 1 + crates/ui-egui/src/i18n/ko.tsv | 1 + crates/ui-egui/src/i18n/nl.tsv | 1 + crates/ui-egui/src/i18n/pl.tsv | 1 + crates/ui-egui/src/i18n/pt-br.tsv | 1 + crates/ui-egui/src/i18n/ru.tsv | 1 + crates/ui-egui/src/i18n/sv.tsv | 1 + crates/ui-egui/src/i18n/tr.tsv | 1 + crates/ui-egui/src/i18n/uk.tsv | 1 + crates/ui-egui/src/i18n/vi.tsv | 1 + crates/ui-egui/src/i18n/zh-hans.tsv | 1 + crates/ui-egui/src/i18n/zh-hant.tsv | 1 + crates/ui-egui/src/retype_runs.rs | 2 + docs/mcp.md | 5 +- 31 files changed, 240 insertions(+), 26 deletions(-) diff --git a/crates/engine/src/cmd/retype.rs b/crates/engine/src/cmd/retype.rs index 9cef3250e9..b4a4de0abb 100644 --- a/crates/engine/src/cmd/retype.rs +++ b/crates/engine/src/cmd/retype.rs @@ -1152,18 +1152,25 @@ fn retype(s: &mut Session, p: &Value) -> Result { pieces.iter().filter(|pc| !pc.keeps_outline).filter_map(|pc| vectorcraft_text::retype::shape_key(&pc.path)).collect(); // Nothing to match (every shape stays an outline): no font is read. let cands = if wanted.is_empty() { vec![] } else { candidate_faces(db, d, &fonts) }; - let compared: Vec = cands.iter().map(|f| f.id()).collect(); + let mut compared: Vec = cands.iter().map(|f| f.id()).collect(); let index = if wanted.is_empty() { RetypeIndex::default() } else { RetypeIndex::build(db, cands, &wanted) }; let mut found: Vec> = pieces.iter().map(|pc| if pc.keeps_outline { vec![] } else { index.matches(&pc.path) }).collect(); - // Shapes no face matched are compared with the installed fonts not loaded yet, or with - // what a search made off the UI thread found for them. + // Shapes no face matched are compared with the other loaded faces, then with the installed + // fonts not loaded yet; or with what a search made off the UI thread found for them. let installed = match handed { Some(handed) => { - add_installed(db, &pieces, &mut found, &handed, &compared); + add_faces(db, &pieces, &mut found, &handed.faces, &compared); + compared.extend(handed.faces.iter().map(|f| f.id())); + // The shapes still left are compared with the loaded faces the search did not + // compare: none, unless a face was loaded after it looked. + compared.extend(handed.scanned.iter().copied()); + add_loaded_rest(db, &pieces, &mut found, &mut compared)?; handed } - None if search_installed => from_installed(db, &pieces, &mut found)?, - None => installed::Installed::default(), + None => { + add_loaded_rest(db, &pieces, &mut found, &mut compared)?; + if search_installed { from_installed(db, &pieces, &mut found)? } else { installed::Installed::default() } + } }; // The face most shapes match, so a glyph several fonts share is set in the same font as // the glyphs around it. @@ -1370,25 +1377,43 @@ fn retype(s: &mut Session, p: &Value) -> Result { /// Every shape that may become type then also gets its matches in the faces found, after the ones /// `found` holds. fn from_installed(db: &FontDb, pieces: &[Piece], found: &mut [Vec]) -> Result { - let left: Vec<&BezPath> = pieces.iter().zip(found.iter()).filter(|(pc, ms)| !pc.keeps_outline && ms.is_empty()).map(|(pc, _)| &pc.path).collect(); - let installed = installed::search(db, &left, false)?; - add_installed(db, pieces, found, &installed, &[]); + let installed = installed::search(db, &left_shapes(pieces, found), false)?; + add_faces(db, pieces, found, &installed.faces, &[]); Ok(installed) } -/// Gives every shape of `pieces` that may become type its matches in the faces `installed` found, -/// after the ones `found` holds, leaving out the faces of `compared` (the faces `found` comes -/// from), whose matches it holds already. -fn add_installed(db: &FontDb, pieces: &[Piece], found: &mut [Vec], installed: &installed::Installed, compared: &[u32]) { - let faces: Vec<_> = installed.faces.iter().filter(|f| !compared.contains(&f.id())).cloned().collect(); +/// Gives the shapes of `pieces` that `found` holds no glyph for their matches in the loaded faces +/// not among `compared` ([`installed::loaded_rest`]), as [`add_faces`] does, and adds those faces +/// to `compared`. +fn add_loaded_rest(db: &FontDb, pieces: &[Piece], found: &mut [Vec], compared: &mut Vec) -> Result<()> { + let rest = installed::loaded_rest(db, &left_shapes(pieces, found), compared)?; + add_faces(db, pieces, found, &rest, compared); + compared.extend(rest.iter().map(|f| f.id())); + Ok(()) +} + +/// The shapes of `pieces` that may become type and that `found` holds no glyph for. +fn left_shapes<'a>(pieces: &'a [Piece], found: &[Vec]) -> Vec<&'a BezPath> { + pieces.iter().zip(found.iter()).filter(|(pc, ms)| !pc.keeps_outline && ms.is_empty()).map(|(pc, _)| &pc.path).collect() +} + +/// Gives every shape of `pieces` that may become type its matches in `faces`, after the ones +/// `found` holds, leaving out the faces of `compared` (the faces `found` comes from), whose +/// matches it holds already. The faces are compared [`MAX_FACES`] at a time, so none is left out. +/// +/// [`MAX_FACES`]: vectorcraft_text::retype::MAX_FACES +fn add_faces(db: &FontDb, pieces: &[Piece], found: &mut [Vec], faces: &[Arc], compared: &[u32]) { + let faces: Vec<_> = faces.iter().filter(|f| !compared.contains(&f.id())).cloned().collect(); if faces.is_empty() { return; } let keys: std::collections::BTreeSet = pieces.iter().filter(|pc| !pc.keeps_outline).filter_map(|pc| vectorcraft_text::retype::shape_key(&pc.path)).collect(); - let index = RetypeIndex::build(db, faces, &keys); - for (pc, ms) in pieces.iter().zip(found.iter_mut()).filter(|(pc, _)| !pc.keeps_outline) { - ms.extend(index.matches(&pc.path)); + for group in faces.chunks(vectorcraft_text::retype::MAX_FACES) { + let index = RetypeIndex::build(db, group.iter().cloned(), &keys); + for (pc, ms) in pieces.iter().zip(found.iter_mut()).filter(|(pc, _)| !pc.keeps_outline) { + ms.extend(index.matches(&pc.path)); + } } } diff --git a/crates/engine/src/cmd/retype_fonts.rs b/crates/engine/src/cmd/retype_fonts.rs index bdbceb57a2..a9696e9ae8 100644 --- a/crates/engine/src/cmd/retype_fonts.rs +++ b/crates/engine/src/cmd/retype_fonts.rs @@ -115,7 +115,10 @@ pub(super) fn rank_fonts( } else if !search_installed { Installed::default() } else if room == 0 { - Installed { skipped: db.unloaded_installed_faces().len(), ..Default::default() } + // The list is full: the installed faces a search would compare count as skipped, none + // when no shape would start one. + let skipped = if super::installed::starts_search(shapes) { db.unloaded_installed_faces().len() } else { 0 }; + Installed { skipped, ..Default::default() } } else { super::installed::search_listed(db, shapes, room, &|f| by_name(db, f))? }; diff --git a/crates/engine/src/cmd/retype_installed.rs b/crates/engine/src/cmd/retype_installed.rs index 6a40ba5791..9bb0e6113d 100644 --- a/crates/engine/src/cmd/retype_installed.rs +++ b/crates/engine/src/cmd/retype_installed.rs @@ -50,6 +50,9 @@ pub(super) struct Installed { pub(super) read: usize, /// Faces left out by the limits ([`LIMITS`]). pub(super) skipped: usize, + /// For a search made away from its command, the ids of the loaded faces it compared: the + /// command does not compare them again. + pub(super) scanned: Vec, } impl Installed { @@ -74,6 +77,37 @@ pub(super) fn search_listed(db: &FontDb, shapes: &[&BezPath], faces: usize, list search_within(db, shapes, true, Limits { faces: faces.min(MAX_FACES), ..LIMITS }, listed) } +/// Would a search for `shapes` read any installed file: is one of them not plain, with a glyph's +/// key ([`shape_key`])? +pub(super) fn starts_search(shapes: &[&BezPath]) -> bool { + shapes.iter().any(|s| !is_plain(s) && shape_key(s).is_some()) +} + +/// The loaded faces that are not among `compared` (those past the [`MAX_FACES`] a Retype compares +/// first) whose glyphs match one of `shapes` that is not plain ([`is_plain`]), compared +/// [`MAX_FACES`] at a time. A cancel stops it between those groups. +pub(super) fn loaded_rest(db: &FontDb, shapes: &[&BezPath], compared: &[u32]) -> Result>> { + let shapes: Vec<&BezPath> = shapes.iter().copied().filter(|s| !is_plain(s)).collect(); + let keys: BTreeSet = shapes.iter().filter_map(|s| shape_key(s)).collect(); + let mut out: Vec> = vec![]; + if keys.is_empty() { + return Ok(out); + } + let rest: Vec> = db.loaded_faces().into_iter().filter(|f| !compared.contains(&f.id())).collect(); + for group in rest.chunks(MAX_FACES) { + vectorcraft_doc::cancel::check()?; + let index = RetypeIndex::build(db, group.iter().cloned(), &keys); + for s in &shapes { + for m in index.all_matches(s) { + if !out.iter().any(|f| f.id() == m.face.id()) { + out.push(m.face); + } + } + } + } + Ok(out) +} + /// An installed font file: its path, its length and the (family, style) of the faces wanted from it. type File = (std::path::PathBuf, u64, Vec<(String, String)>); @@ -122,7 +156,7 @@ fn search_within(db: &FontDb, shapes: &[&BezPath], every: bool, limits: Limits, for (j, face) in faces.iter().enumerate() { if out.faces.len() >= limits.faces { // The faces not compared past the cap: the rest of this file's and the later files'. - out.skipped += faces.len() - j + files.iter().skip(i + 1).map(|f| f.2.len()).sum::(); + out.skipped += styles.len().saturating_sub(j) + files.iter().skip(i + 1).map(|f| f.2.len()).sum::(); return Ok(out); } let n = encoded_glyphs(face); @@ -151,9 +185,12 @@ fn search_within(db: &FontDb, shapes: &[&BezPath], every: bool, limits: Limits, if fits.is_empty() { continue; } - remember(db, &loaded); - if listed(&loaded) && !out.faces.iter().any(|f| f.id() == loaded.id()) { - out.faces.push(loaded); + // A face `listed` turns down (another version shadows it) is not compared ahead of others. + if listed(&loaded) { + remember(db, &loaded); + if !out.faces.iter().any(|f| f.id() == loaded.id()) { + out.faces.push(loaded); + } } for k in fits { if let Some(m) = matched.get_mut(k) { @@ -237,8 +274,9 @@ pub struct RetypeSearch { faces: Vec>, } -/// What a [`RetypeSearch`] found in the installed fonts: the faces whose glyphs match, loaded, and -/// what it read. +/// What a [`RetypeSearch`] found: for `type.retype`, the faces it compared first that match, the +/// loaded faces past those that match ([`loaded_rest`]), the installed faces whose glyphs match, +/// loaded, and the loaded faces it compared; and what it read of the installed fonts. pub struct RetypeFound { doc: u64, installed: Installed, @@ -252,6 +290,12 @@ impl RetypeFound { s.retype_hand_off = Some(self); } + /// Drop what was handed in and no command took, as when the command failed before it took + /// it: a later command searches for itself. + pub fn drop_handed(s: &mut Session) { + s.retype_hand_off = None; + } + /// What it read, as the commands report it. pub fn json(&self) -> Value { self.installed.json() @@ -352,7 +396,29 @@ impl RetypeSearch { let keys: BTreeSet = shapes.iter().filter_map(|sh| shape_key(sh)).collect(); let index = RetypeIndex::build(db, self.faces.iter().cloned(), &keys); let left: Vec<&BezPath> = shapes.iter().copied().filter(|sh| index.matches(sh).is_empty()).collect(); - search(db, &left, false)? + // The first faces that match are handed in too: loading the faces found can move one + // past the first 96 the command compares. + let mut first: Vec> = vec![]; + for m in shapes.iter().flat_map(|sh| index.all_matches(sh)) { + if !first.iter().any(|f| f.id() == m.face.id()) { + first.push(m.face); + } + } + // The loaded faces past the ones compared first, then the installed fonts for what + // none of them matches; the command takes both from what is handed in. + let compared: Vec = self.faces.iter().map(|f| f.id()).collect(); + // Every face loaded now is compared, among the first ones or with the rest. + let scanned: Vec = compared.iter().copied().chain(db.loaded_faces().iter().map(|f| f.id())).collect(); + let rest = loaded_rest(db, &left, &compared)?; + let mut left = left; + for group in rest.chunks(MAX_FACES) { + let index = RetypeIndex::build(db, group.iter().cloned(), &keys); + left.retain(|sh| index.matches(sh).is_empty()); + } + let mut found = search(db, &left, false)?; + found.faces.splice(0..0, first.into_iter().chain(rest)); + found.scanned = scanned; + found }; Ok(RetypeFound { doc: self.doc, installed }) } diff --git a/crates/engine/src/cmd/retype_installed_tests.rs b/crates/engine/src/cmd/retype_installed_tests.rs index 633028a42c..0bea2c620c 100644 --- a/crates/engine/src/cmd/retype_installed_tests.rs +++ b/crates/engine/src/cmd/retype_installed_tests.rs @@ -192,6 +192,9 @@ fn faces_a_list_turns_down_are_loaded_and_take_no_place() { assert_eq!(families, ["Retype Copy S", "Retype Copy T"]); assert_eq!((found.read, found.skipped), (3, 0)); assert!(!unloaded(&db, "Retype Copy R"), "the face turned down was loaded"); + // Only the faces listed are compared ahead of the other loaded faces later. + let ahead: Vec = super::found(&db).iter().map(|f| f.family.clone()).collect(); + assert!(ahead.iter().any(|f| f == "Retype Copy S") && !ahead.iter().any(|f| f == "Retype Copy R"), "{ahead:?}"); } #[test] @@ -357,3 +360,90 @@ fn installed_must_be_a_bool_or_null() { let r = s.execute("type.retypeFonts", &json!({"installed": false})).unwrap(); assert_eq!(r["installed"], json!({"read": 0, "skipped": 0}), "{r}"); } + +/// A database with no installed fonts and `n` copies of the bundled Source Sans 3 Regular loaded, +/// named `{tag} 0` to `{tag} n-1`, after `inter` copies of Inter named `{tag} Inter 0` and on. +fn loaded_copies(tag: &str, inter: usize, n: usize) -> FontDb { + let db = FontDb::with_font_dirs(vec![]); + let copies = (0..inter).map(|i| (true, format!("{tag} Inter {i}"))).chain((0..n).map(|i| (false, format!("{tag} {i}")))); + for (inter, family) in copies { + let postscript = format!("{}-Regular", family.replace(' ', "")); + db.add_font(vectorcraft_text::test_fonts::named_copy(inter, (&family, "Regular", "Version 1.000", &postscript)).unwrap()); + } + db +} + +#[test] +fn loaded_faces_past_the_ones_compared_first_are_compared_too() { + let n = vectorcraft_text::retype::MAX_FACES + 4; + let db = loaded_copies("Retype Rest", 0, n); + let shapes = glyphs(&db, "Rx"); + let refs: Vec<&BezPath> = shapes.iter().collect(); + // Every loaded face that matches, more than one index takes. + let rest = super::loaded_rest(&db, &refs, &[]).unwrap(); + for i in 0..n { + assert!(rest.iter().any(|f| f.family == format!("Retype Rest {i}")), "copy {i} of {}", rest.len()); + } + // The faces compared already are left out. + let last = format!("Retype Rest {}", n - 1); + let compared: Vec = db.loaded_faces().iter().filter(|f| f.family != last).map(|f| f.id()).collect(); + let rest = super::loaded_rest(&db, &refs, &compared).unwrap(); + assert_eq!(rest.iter().map(|f| f.family.as_str()).collect::>(), [last.as_str()]); + // A plain shape alone compares none. + let bar = [kurbo::Rect::new(0.0, 0.0, 80.0, 10.0).to_path(0.1)]; + assert!(super::loaded_rest(&db, &[&bar[0]], &[]).unwrap().is_empty()); +} + +#[test] +fn a_run_away_from_the_command_hands_in_the_loaded_faces_past_the_ones_compared_first() { + let db = loaded_copies("Retype Run Rest", vectorcraft_text::retype::MAX_FACES, 1); + let shapes = glyphs(&db, "Rx"); + // The Inter copies are compared first: none matches, and the copy loaded after them does. + let faces: Vec<_> = db.loaded_faces().into_iter().filter(|f| f.family.starts_with("Retype Run Rest Inter")).collect(); + assert_eq!(faces.len(), vectorcraft_text::retype::MAX_FACES); + let search = super::RetypeSearch { command: "type.retype", doc: 1, shapes: shapes.clone(), faces }; + let found = search.run_in(&db).unwrap(); + assert!(found.installed.faces.iter().any(|f| f.family == "Retype Run Rest 0"), "the loaded copy is handed in"); + assert_eq!((found.installed.read, found.installed.skipped), (0, 0), "no installed file is read for it"); + // Every loaded face was compared: the command does not compare them again. + assert!(db.loaded_faces().iter().all(|f| found.installed.scanned.contains(&f.id()))); + // A face compared first that matches is handed in too, as loading others may move it past + // the faces the command compares first. + let copy: Vec<_> = db.loaded_faces().into_iter().filter(|f| f.family == "Retype Run Rest 0").collect(); + let found = super::RetypeSearch { command: "type.retype", doc: 1, shapes, faces: copy }.run_in(&db).unwrap(); + assert_eq!(found.installed.faces.first().map(|f| f.family.as_str()), Some("Retype Run Rest 0")); +} + +#[test] +fn a_full_list_counts_skipped_installed_faces_only_when_a_shape_would_start_a_search() { + let (db, _) = installed("full-list", &["Retype Copy Full"]); + for i in 0..super::super::fonts::MAX_COUNT { + let family = format!("Retype Full {i}"); + let postscript = format!("RetypeFull{i}-Regular"); + db.add_font(vectorcraft_text::test_fonts::named_copy(false, (&family, "Regular", "Version 1.000", &postscript)).unwrap()); + } + let faces: Vec<_> = db.loaded_faces().into_iter().filter(|f| f.family.starts_with("Retype Full ")).collect(); + // A hyphen is plain: it fills the list and would start no search, so nothing is skipped. + let hyphen = glyphs(&db, "-"); + let refs: Vec<&BezPath> = hyphen.iter().collect(); + let (ranked, found) = super::super::fonts::rank_fonts(&db, faces.clone(), &refs, true, None).unwrap(); + assert_eq!(ranked.len(), super::super::fonts::MAX_COUNT); + assert_eq!((found.read, found.skipped), (0, 0)); + // A shape that is not plain would: the installed face counts as skipped. + let shapes = glyphs(&db, "-q"); + let refs: Vec<&BezPath> = shapes.iter().collect(); + let (_, found) = super::super::fonts::rank_fonts(&db, faces, &refs, true, None).unwrap(); + assert_eq!((found.read, found.skipped), (0, 1)); + assert!(unloaded(&db, "Retype Copy Full")); +} + +#[test] +fn what_is_handed_in_and_not_taken_can_be_dropped() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 600, "height": 400})).unwrap(); + let doc = s.doc().unwrap().uid; + super::RetypeFound { doc, installed: super::Installed::default() }.hand_in(&mut s); + assert!(s.retype_hand_off.is_some()); + super::RetypeFound::drop_handed(&mut s); + assert!(s.retype_hand_off.is_none()); +} diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index e7b5b805a9..d2058f9f6e 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -7649,6 +7649,7 @@ variable-list-end {0}, {1} {0} i {1} @msg {_1} files {_1} fitxers @msg {_1} files are written by file.saveAsTemplate els fitxers {_1} els escriu file.saveAsTemplate @msg {_1} files can be opened but not written (see document.formats) els fitxers {_1} es poden obrir però no escriure (consulta document.formats) +@msg Retype failed: internal error: its thread stopped (please report this bug) Torna a escriure ha fallat: error intern: el seu fil s'ha aturat (informeu d'aquest error) @msg Retype finished, but the document or its selection changed meanwhile: run it again Torna a escriure ha acabat, però el document o la seva selecció ha canviat mentrestant: torna-ho a executar @msg {_1} finished, but the document or the plug-in changed meanwhile: run it again {_1} ha acabat, però el document o el complement ha canviat mentrestant: torna-ho a executar @msg {_1} font families available {_1} famílies de tipus de lletra disponibles diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index 52bf5c3c2c..a23205c2c2 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -8939,6 +8939,7 @@ breakText Glyphs Glyfy @msg Image Trace failed: internal error: its thread stopped (please report this bug) Vektorizace obrazu selhala: vnitřní chyba: její vlákno se zastavilo (nahlaste prosím tuto chybu) @msg Image Trace failed: {e} Vektorizace obrazu selhala: {e} @msg Image Trace finished, but its document was closed Vektorizace obrazu skončila, ale její dokument byl zavřen +@msg Retype failed: internal error: its thread stopped (please report this bug) Přepsání selhalo: vnitřní chyba: jeho vlákno se zastavilo (nahlaste prosím tuto chybu) @msg Retype finished, but the document or its selection changed meanwhile: run it again Přepsání skončilo, ale dokument nebo jeho výběr se mezitím změnil: spusťte ho znovu @msg Image Trace finished, but the image or its settings changed meanwhile: trace it again Vektorizace obrazu skončila, ale obraz nebo jeho nastavení se mezitím změnily: vektorizujte ho znovu @msg Image Trace finished, but its document was reverted: trace it again Vektorizace obrazu skončila, ale její dokument byl vrácen k uložené verzi: vektorizujte ho znovu diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index cb8e37b4fb..91b833fa02 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -1010,6 +1010,7 @@ liquify-list-end {0}, {1} {0} og {1} @msg Image Trace failed: {e} Billedsporing mislykkedes: {e} @msg Image Trace finished, but its document was closed Billedsporing blev færdig, men dens dokument blev lukket @msg Image Trace finished, but its document was reverted: trace it again Billedsporing blev færdig, men dens dokument blev gendannet: spor det igen +@msg Retype failed: internal error: its thread stopped (please report this bug) Genindtast mislykkedes: intern fejl: dens tråd stoppede (rapportér venligst denne fejl) @msg Retype finished, but the document or its selection changed meanwhile: run it again Genindtast blev færdig, men dokumentet eller dets markering ændrede sig imens: kør det igen @msg Image Trace finished, but the image or its settings changed meanwhile: trace it again Billedsporing blev færdig, men billedet eller dets indstillinger ændrede sig imens: spor det igen @msg Import SVG Filter reads SVG files, not SVGZ Importér SVG-filter læser SVG-filer, ikke SVGZ diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index 64d064bd4c..521b41958e 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -8823,6 +8823,7 @@ breakText Glyphs Glyphen @msg Image Trace failed: internal error: its thread stopped (please report this bug) Bildnachzeichner fehlgeschlagen: interner Fehler: Sein Thread wurde beendet (bitte melden Sie diesen Fehler) @msg Image Trace failed: {e} Bildnachzeichner fehlgeschlagen: {e} @msg Image Trace finished, but its document was closed Bildnachzeichner abgeschlossen, aber sein Dokument wurde geschlossen +@msg Retype failed: internal error: its thread stopped (please report this bug) Neu setzen fehlgeschlagen: interner Fehler: Sein Thread wurde beendet (bitte melden Sie diesen Fehler) @msg Retype finished, but the document or its selection changed meanwhile: run it again Neu setzen abgeschlossen, aber das Dokument oder seine Auswahl hat sich inzwischen geändert: Führen Sie es erneut aus @msg Image Trace finished, but the image or its settings changed meanwhile: trace it again Bildnachzeichner abgeschlossen, aber das Bild oder seine Einstellungen haben sich inzwischen geändert: Zeichnen Sie es erneut nach @msg Image Trace finished, but its document was reverted: trace it again Bildnachzeichner abgeschlossen, aber sein Dokument wurde auf die letzte Version zurückgesetzt: Zeichnen Sie es erneut nach diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index 71b62d4adf..ad582eecfa 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -7285,6 +7285,7 @@ axis Y Axis Άξονας Y The plug-in is computing… Το πρόσθετο υπολογίζει… Inspect Plug-in Επιθεώρηση προσθέτου Cancel Plug-in Run Ακύρωση εκτέλεσης προσθέτου +@msg Retype failed: internal error: its thread stopped (please report this bug) Η Επαναπληκτρολόγηση απέτυχε: εσωτερικό σφάλμα: το νήμα της σταμάτησε (αναφέρετε αυτό το σφάλμα) @msg Retype finished, but the document or its selection changed meanwhile: run it again Η Επαναπληκτρολόγηση ολοκληρώθηκε, αλλά το έγγραφο ή η επιλογή του άλλαξε στο μεταξύ: εκτελέστε την ξανά @msg {_1} finished, but the document or the plug-in changed meanwhile: run it again Το {_1} ολοκληρώθηκε, αλλά το έγγραφο ή το πρόσθετο άλλαξε στο μεταξύ: εκτελέστε το ξανά @msg Running “{name}”… Εκτέλεση του «{name}»… diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index 3619c9fff8..7b091e3fe9 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -9267,6 +9267,7 @@ breakText Glyphs Glifos @msg Image Trace failed: internal error: its thread stopped (please report this bug) Error de Calco de imagen: error interno: su hilo se detuvo (informa de este error) @msg Image Trace failed: {e} Error de Calco de imagen: {e} @msg Image Trace finished, but its document was closed Calco de imagen terminó, pero su documento se cerró +@msg Retype failed: internal error: its thread stopped (please report this bug) Error de Reescribir: error interno: su hilo se detuvo (informa de este error) @msg Retype finished, but the document or its selection changed meanwhile: run it again Reescribir terminó, pero el documento o su selección cambiaron mientras tanto: ejecútalo de nuevo @msg Image Trace finished, but the image or its settings changed meanwhile: trace it again Calco de imagen terminó, pero la imagen o sus ajustes cambiaron mientras tanto: cálcala de nuevo @msg Invalid dimension offset Desplazamiento de cota no válido diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index 88edeba695..7eae850873 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -7362,6 +7362,7 @@ axis Y Axis Y-akseli The plug-in is computing… Laajennus laskee… Inspect Plug-in Tarkastele laajennusta Cancel Plug-in Run Peruuta laajennuksen ajo +@msg Retype failed: internal error: its thread stopped (please report this bug) Kirjoita uudelleen epäonnistui: sisäinen virhe: sen säie pysähtyi (ilmoita tästä virheestä) @msg Retype finished, but the document or its selection changed meanwhile: run it again Kirjoita uudelleen valmistui, mutta asiakirja tai sen valinta muuttui sillä välin: suorita se uudelleen @msg {_1} finished, but the document or the plug-in changed meanwhile: run it again {_1} valmistui, mutta asiakirja tai laajennus muuttui sillä välin: suorita se uudelleen @msg Running “{name}”… Suoritetaan ”{name}”… diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 3581a0a211..748d6f5789 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -8808,6 +8808,7 @@ breakText Glyphs Glyphes @msg Image Trace failed: {e} Échec de la vectorisation de l’image : {e} @msg Image Trace finished, but its document was closed La vectorisation de l’image est terminée, mais son document a été fermé @msg Image Trace finished, but its document was reverted: trace it again La vectorisation de l’image est terminée, mais son document a été rétabli à la version précédente : vectorisez-la à nouveau +@msg Retype failed: internal error: its thread stopped (please report this bug) Échec de Retaper. Erreur interne. Son thread s’est arrêté (merci de signaler ce bogue) @msg Retype finished, but the document or its selection changed meanwhile: run it again Retaper est terminé, mais le document ou sa sélection a changé entre-temps. Relancez-le @msg Image Trace finished, but the image or its settings changed meanwhile: trace it again La vectorisation de l’image est terminée, mais l’image ou ses réglages ont changé entre-temps : vectorisez-la à nouveau @msg Import SVG Filter reads SVG files, not SVGZ Importer un filtre SVG lit les fichiers SVG, pas SVGZ diff --git a/crates/ui-egui/src/i18n/hi.tsv b/crates/ui-egui/src/i18n/hi.tsv index 4ddb098c1a..b8b323e1dc 100644 --- a/crates/ui-egui/src/i18n/hi.tsv +++ b/crates/ui-egui/src/i18n/hi.tsv @@ -8067,6 +8067,7 @@ liquify-list-end {0}, {1} {0} और {1} @msg Image Trace failed: {e} इमेज ट्रेस विफल: {e} @msg Image Trace failed: internal error: its thread stopped (please report this bug) इमेज ट्रेस विफल: आंतरिक त्रुटि: इसके धागे को बंद कर दिया (कृपया इस बग की रिपोर्ट करें) @msg Image Trace finished, but its document was closed इमेज ट्रेस समाप्त हो गया, लेकिन इसका डॉक्यूमेंट बंद हो गया। +@msg Retype failed: internal error: its thread stopped (please report this bug) फिर से टाइप करना विफल: आंतरिक त्रुटि: इसका थ्रेड रुक गया (कृपया इस बग की रिपोर्ट करें) @msg Retype finished, but the document or its selection changed meanwhile: run it again फिर से टाइप करना समाप्त हो गया, लेकिन इस बीच दस्तावेज़ या उसका चयन बदल गया: इसे फिर से चलाएँ @msg Image Trace finished, but the image or its settings changed meanwhile: trace it again इमेज ट्रेस समाप्त हो गया, लेकिन इस बीच इमेज या इसकी सेटिंग्स बदल गई: इसे फिर से ट्रेस करें @msg Image Trace finished, but its document was reverted: trace it again इमेज ट्रेस समाप्त हो गया, लेकिन इसके डॉक्यूमेंट को मूल स्थिति में लाया गया: इसे फिर से ट्रेस करें diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index 393720cd19..fb5bbeb169 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -8810,6 +8810,7 @@ breakText Glyphs Glifák @msg Image Trace failed: internal error: its thread stopped (please report this bug) A képvektorizálás nem sikerült: belső hiba: a szála leállt (kérjük, jelentsd ezt a hibát) @msg Image Trace failed: {e} A képvektorizálás nem sikerült: {e} @msg Image Trace finished, but its document was closed A képvektorizálás elkészült, de a dokumentumát bezárták +@msg Retype failed: internal error: its thread stopped (please report this bug) Az újragépelés nem sikerült: belső hiba: a szála leállt (kérjük, jelentsd ezt a hibát) @msg Retype finished, but the document or its selection changed meanwhile: run it again Az újragépelés elkészült, de a dokumentum vagy a kijelölése közben megváltozott: futtasd újra @msg Image Trace finished, but the image or its settings changed meanwhile: trace it again A képvektorizálás elkészült, de a kép vagy a beállításai közben megváltoztak: vektorizáld újra @msg Image Trace finished, but its document was reverted: trace it again A képvektorizálás elkészült, de a dokumentumát visszaállították a mentett változatra: vektorizáld újra diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index b7ef9a298e..ad1c077d66 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -409,6 +409,7 @@ @msg `spread` must be pad, repeat or reflect `spread` harus pad, repeat atau reflect @msg `repeats` must be a whole number from 1 to {MAX_REPEATS} `repeats` harus berupa bilangan bulat dari 1 sampai {MAX_REPEATS} @msg `spread` applies to linear, radial, conic and diamond gradients `spread` berlaku untuk gradien linear, radial, conic, dan diamond +@msg Retype failed: internal error: its thread stopped (please report this bug) Ketik Ulang gagal: kesalahan internal: utasnya berhenti (harap laporkan bug ini) @msg Retype finished, but the document or its selection changed meanwhile: run it again Ketik Ulang selesai, tetapi dokumen atau pilihannya berubah sementara itu: jalankan lagi @msg {_1} finished, but the document or the plug-in changed meanwhile: run it again {_1} selesai, tetapi dokumen atau plug-in berubah sementara itu: jalankan lagi @msg Running “{name}”… Menjalankan “{name}”… diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index 59a068be66..9501f4177f 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -8876,6 +8876,7 @@ breakText Glyphs Glifi @msg Image Trace failed: internal error: its thread stopped (please report this bug) Ricalco immagine non riuscito: errore interno: il suo thread si è fermato (segnala questo bug) @msg Image Trace failed: {e} Ricalco immagine non riuscito: {e} @msg Image Trace finished, but its document was closed Ricalco immagine terminato, ma il suo documento è stato chiuso +@msg Retype failed: internal error: its thread stopped (please report this bug) Ridigita non riuscito: errore interno: il suo thread si è fermato (segnala questo bug) @msg Retype finished, but the document or its selection changed meanwhile: run it again Ridigita terminato, ma nel frattempo il documento o la sua selezione sono cambiati: eseguilo di nuovo @msg Image Trace finished, but the image or its settings changed meanwhile: trace it again Ricalco immagine terminato, ma nel frattempo l'immagine o le sue impostazioni sono cambiate: ricalcala di nuovo @msg Image Trace finished, but its document was reverted: trace it again Ricalco immagine terminato, ma il suo documento è stato ripristinato: ricalcala di nuovo diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index a2b4d8f47a..647dfe9659 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -7693,6 +7693,7 @@ axis Y Axis Y 軸 @msg Image Trace failed: internal error: its thread stopped (please report this bug) 画像トレースに失敗しました: 内部エラー: スレッドが停止しました (このバグを報告してください) @msg Image Trace failed: {e} 画像トレースに失敗しました: {e} @msg Image Trace finished, but its document was closed 画像トレースは完了しましたが、ドキュメントが閉じられています +@msg Retype failed: internal error: its thread stopped (please report this bug) リタイプに失敗しました: 内部エラー: スレッドが停止しました (このバグを報告してください) @msg Retype finished, but the document or its selection changed meanwhile: run it again リタイプは完了しましたが、その間にドキュメントまたは選択範囲が変更されました: もう一度実行してください @msg Image Trace finished, but the image or its settings changed meanwhile: trace it again 画像トレースは完了しましたが、その間に画像または設定が変更されました: もう一度トレースしてください @msg Image Trace finished, but its document was reverted: trace it again 画像トレースは完了しましたが、ドキュメントは保存済みの状態に戻されました: もう一度トレースしてください diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index 2d6269338c..e8bae7c552 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -89,6 +89,7 @@ @msg Image Trace failed: internal error: its thread stopped (please report this bug) გამოსახულების ვექტორიზაცია ვერ მოხერხდა: შიდა შეცდომა: მისი ნაკადი შეჩერდა (გთხოვთ, შეგვატყობინოთ ამ ხარვეზის შესახებ) @msg Image Trace failed: {e} გამოსახულების ვექტორიზაცია ვერ მოხერხდა: {e} @msg Image Trace finished, but its document was closed გამოსახულების ვექტორიზაცია დასრულდა, მაგრამ მისი დოკუმენტი დაიხურა +@msg Retype failed: internal error: its thread stopped (please report this bug) ხელახლა აკრეფა ვერ მოხერხდა: შიდა შეცდომა: მისი ნაკადი შეჩერდა (გთხოვთ, შეგვატყობინოთ ამ ხარვეზის შესახებ) @msg Retype finished, but the document or its selection changed meanwhile: run it again ხელახლა აკრეფა დასრულდა, მაგრამ ამასობაში დოკუმენტი ან მისი მონიშვნა შეიცვალა: გაუშვით ხელახლა @msg Image Trace finished, but the image or its settings changed meanwhile: trace it again გამოსახულების ვექტორიზაცია დასრულდა, მაგრამ ამასობაში გამოსახულება ან მისი პარამეტრები შეიცვალა: გაუშვით ვექტორიზაცია ხელახლა @msg Import SVG Filter reads SVG files, not SVGZ „SVG ფილტრის იმპორტი“ კითხულობს SVG ფაილებს და არა SVGZ-ს diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index 80ef7b8d34..28c01573f2 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -8578,6 +8578,7 @@ breakText Glyphs 글리프 @msg Image Trace failed: internal error: its thread stopped (please report this bug) 이미지 추적 실패: 내부 오류: 스레드가 멈췄습니다(이 버그를 보고해 주세요) @msg Image Trace failed: {e} 이미지 추적 실패: {e} @msg Image Trace finished, but its document was closed 이미지 추적이 끝났지만 문서가 닫혔습니다 +@msg Retype failed: internal error: its thread stopped (please report this bug) 리타입 실패: 내부 오류: 스레드가 멈췄습니다(이 버그를 보고해 주세요) @msg Retype finished, but the document or its selection changed meanwhile: run it again 리타입이 끝났지만 그 사이에 문서나 선택 영역이 바뀌었습니다: 다시 실행하세요 @msg Image Trace finished, but the image or its settings changed meanwhile: trace it again 이미지 추적이 끝났지만 그 사이에 이미지나 설정이 바뀌었습니다: 다시 추적하세요 @msg Image Trace finished, but its document was reverted: trace it again 이미지 추적이 끝났지만 문서가 되돌려졌습니다: 다시 추적하세요 diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index e2e87b02dc..ce227754b7 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -6445,6 +6445,7 @@ imageTrace Outline Contour @msg Image Trace failed: internal error: its thread stopped (please report this bug) Afbeelding traceren is mislukt: interne fout: de thread ervan is gestopt (meld deze bug alsjeblieft) @msg Image Trace failed: {e} Afbeelding traceren is mislukt: {e} @msg Image Trace finished, but its document was closed Afbeelding traceren is voltooid, maar het document ervan is gesloten +@msg Retype failed: internal error: its thread stopped (please report this bug) Opnieuw typen is mislukt: interne fout: de thread ervan is gestopt (meld deze bug alsjeblieft) @msg Retype finished, but the document or its selection changed meanwhile: run it again Opnieuw typen is voltooid, maar het document of de selectie ervan is intussen gewijzigd: voer het opnieuw uit @msg Image Trace finished, but the image or its settings changed meanwhile: trace it again Afbeelding traceren is voltooid, maar de afbeelding of de instellingen ervan zijn intussen gewijzigd: traceer de afbeelding opnieuw @msg Image Trace finished, but its document was reverted: trace it again Afbeelding traceren is voltooid, maar het document ervan is teruggezet: traceer de afbeelding opnieuw diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index 889f0f3ef3..1da69847ea 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -9086,6 +9086,7 @@ breakText Glyphs Glify @msg Image Trace failed: internal error: its thread stopped (please report this bug) Obrys obrazu nie powiódł się: błąd wewnętrzny: jego wątek został zatrzymany (zgłoś ten błąd) @msg Image Trace failed: {e} Obrys obrazu nie powiódł się: {e} @msg Image Trace finished, but its document was closed Obrys obrazu został ukończony, ale jego dokument został zamknięty +@msg Retype failed: internal error: its thread stopped (please report this bug) Przepisywanie nie powiodło się: błąd wewnętrzny: jego wątek został zatrzymany (zgłoś ten błąd) @msg Retype finished, but the document or its selection changed meanwhile: run it again Przepisywanie zostało ukończone, ale dokument lub jego zaznaczenie zmieniły się w międzyczasie: uruchom je ponownie @msg Image Trace finished, but the image or its settings changed meanwhile: trace it again Obrys obrazu został ukończony, ale obraz lub jego ustawienia zmieniły się w międzyczasie: obrysuj go ponownie @msg Image Trace finished, but its document was reverted: trace it again Obrys obrazu został ukończony, ale jego dokument został przywrócony: obrysuj go ponownie diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index a59bd7944a..a4d598a735 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -8992,6 +8992,7 @@ swatch Yellow Green Verde-amarelado @msg Image Trace failed: internal error: its thread stopped (please report this bug) O Rastreamento de Imagem falhou: erro interno: a thread dele parou (informe este erro) @msg Image Trace failed: {e} O Rastreamento de Imagem falhou: {e} @msg Image Trace finished, but its document was closed O Rastreamento de Imagem terminou, mas o documento dele foi fechado +@msg Retype failed: internal error: its thread stopped (please report this bug) O Redigitar falhou: erro interno: a thread dele parou (informe este erro) @msg Retype finished, but the document or its selection changed meanwhile: run it again O Redigitar terminou, mas o documento ou a seleção dele mudou nesse meio-tempo: execute-o novamente @msg Image Trace finished, but the image or its settings changed meanwhile: trace it again O Rastreamento de Imagem terminou, mas a imagem ou as configurações dela mudaram nesse meio-tempo: rastreie-a novamente @msg Image Trace finished, but its document was reverted: trace it again O Rastreamento de Imagem terminou, mas o documento dele foi revertido: rastreie-a novamente diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index cdfc4c38ca..05b3170d4a 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -8927,6 +8927,7 @@ shape Open Открытый @msg Image Trace failed: internal error: its thread stopped (please report this bug) Трассировка изображения не выполнена: внутренняя ошибка: её поток остановился (сообщите об этой ошибке) @msg Image Trace failed: {e} Трассировка изображения не выполнена: {e} @msg Image Trace finished, but its document was closed Трассировка изображения завершена, но её документ был закрыт +@msg Retype failed: internal error: its thread stopped (please report this bug) Перенабор не выполнен: внутренняя ошибка: его поток остановился (сообщите об этой ошибке) @msg Retype finished, but the document or its selection changed meanwhile: run it again Перенабор завершён, но документ или его выделение за это время изменились: выполните его снова @msg Image Trace finished, but the image or its settings changed meanwhile: trace it again Трассировка изображения завершена, но изображение или его настройки за это время изменились: выполните трассировку снова @msg Import SVG Filter reads SVG files, not SVGZ Импорт фильтра SVG читает файлы SVG, а не SVGZ diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index 45d255129a..6806e07bdc 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -9369,6 +9369,7 @@ digits Hindi Hindi @msg Image Trace failed: {e} Bildkalkering misslyckades: {e} @msg Image Trace failed: internal error: its thread stopped (please report this bug) Bildkalkering misslyckades: internt fel: dess tråd stoppades (rapportera gärna felet) @msg Image Trace finished, but its document was closed Bildkalkeringen är klar, men dess dokument har stängts +@msg Retype failed: internal error: its thread stopped (please report this bug) Skriv om misslyckades: internt fel: dess tråd stoppades (rapportera gärna felet) @msg Retype finished, but the document or its selection changed meanwhile: run it again Skriv om är klar, men dokumentet eller dess markering ändrades under tiden: kör det igen @msg Image Trace finished, but the image or its settings changed meanwhile: trace it again Bildkalkeringen är klar, men bilden eller dess inställningar ändrades under tiden: vektorisera den igen @msg Image Trace finished, but its document was reverted: trace it again Bildkalkeringen är klar, men dess dokument har återgått till sparad version: vektorisera den igen diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index 57ab2aca77..57b8143bbb 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -8074,6 +8074,7 @@ axis Y Axis Y ekseni @msg Image Trace failed: internal error: its thread stopped (please report this bug) Görüntü İzleme başarısız oldu: iç hata: iş parçacığı durdu (lütfen bu hatayı bildirin) @msg Image Trace failed: {e} Görüntü İzleme başarısız oldu: {e} @msg Image Trace finished, but its document was closed Görüntü İzleme tamamlandı, ancak belgesi kapatılmıştı +@msg Retype failed: internal error: its thread stopped (please report this bug) Yeniden Yaz başarısız oldu: iç hata: iş parçacığı durdu (lütfen bu hatayı bildirin) @msg Retype finished, but the document or its selection changed meanwhile: run it again Yeniden Yaz tamamlandı, ancak bu sırada belge veya seçimi değişti: yeniden çalıştırın @msg Image Trace finished, but the image or its settings changed meanwhile: trace it again Görüntü İzleme tamamlandı, ancak bu sırada görüntü veya ayarları değişti: yeniden izleyin @msg Image Trace finished, but its document was reverted: trace it again Görüntü İzleme tamamlandı, ancak belgesi geri döndürüldü: yeniden izleyin diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index 6720ddfe41..23884ccc72 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -8580,6 +8580,7 @@ breakText Glyphs Гліфи @msg Image Trace failed: internal error: its thread stopped (please report this bug) Трасування зображення не вдалося: внутрішня помилка: його потік зупинився (будь ласка, повідомте про цю помилку) @msg Image Trace failed: {e} Трасування зображення не вдалося: {e} @msg Image Trace finished, but its document was closed Трасування зображення завершено, але його документ закрито +@msg Retype failed: internal error: its thread stopped (please report this bug) Повторний набір не вдався: внутрішня помилка: його потік зупинився (будь ласка, повідомте про цю помилку) @msg Retype finished, but the document or its selection changed meanwhile: run it again Повторний набір завершено, але документ або його виділення тим часом змінилися: виконайте його ще раз @msg Image Trace finished, but the image or its settings changed meanwhile: trace it again Трасування зображення завершено, але зображення або його параметри тим часом змінилися: виконайте трасування ще раз @msg Image Trace finished, but its document was reverted: trace it again Трасування зображення завершено, але його документ було повернуто до збереженої версії: виконайте трасування ще раз diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index a914326a5e..914d9910eb 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -6946,6 +6946,7 @@ axis Y Axis Trục Y The plug-in is computing… Plug-in đang tính toán… Inspect Plug-in Kiểm tra plug-in Cancel Plug-in Run Hủy lần chạy plug-in +@msg Retype failed: internal error: its thread stopped (please report this bug) Gõ lại thất bại: lỗi nội bộ: luồng của nó đã dừng (vui lòng báo cáo lỗi này) @msg Retype finished, but the document or its selection changed meanwhile: run it again Gõ lại đã chạy xong, nhưng tài liệu hoặc vùng chọn của nó đã thay đổi trong lúc đó: hãy chạy lại @msg {_1} finished, but the document or the plug-in changed meanwhile: run it again {_1} đã chạy xong, nhưng tài liệu hoặc plug-in đã thay đổi trong lúc đó: hãy chạy lại @msg Running “{name}”… Đang chạy “{name}”… diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index 0d26776c45..03d67e027a 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -9095,6 +9095,7 @@ breakText Glyphs 字形 @msg Image Trace failed: internal error: its thread stopped (please report this bug) 图像描摹失败:内部错误:其线程已停止 (请报告此错误) @msg Image Trace failed: {e} 图像描摹失败:{e} @msg Image Trace finished, but its document was closed 图像描摹已完成,但其文档已关闭 +@msg Retype failed: internal error: its thread stopped (please report this bug) 重新键入失败:内部错误:其线程已停止 (请报告此错误) @msg Retype finished, but the document or its selection changed meanwhile: run it again 重新键入已完成,但文档或其选区在此期间发生了更改:请重新运行 @msg Image Trace finished, but the image or its settings changed meanwhile: trace it again 图像描摹已完成,但图像或其设置在此期间发生了更改:请重新描摹 @msg Image Trace finished, but its document was reverted: trace it again 图像描摹已完成,但其文档已恢复:请重新描摹 diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index f5ecae2fa9..43bcd5eee0 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -9031,6 +9031,7 @@ breakText Glyphs 字符 @msg Image Trace failed: internal error: its thread stopped (please report this bug) 影像描圖失敗:內部錯誤:其執行緒已停止 (請回報此錯誤) @msg Image Trace failed: {e} 影像描圖失敗:{e} @msg Image Trace finished, but its document was closed 影像描圖已完成,但其文件已關閉 +@msg Retype failed: internal error: its thread stopped (please report this bug) 重新鍵入失敗:內部錯誤:其執行緒已停止 (請回報此錯誤) @msg Retype finished, but the document or its selection changed meanwhile: run it again 重新鍵入已完成,但文件或其選取範圍在此期間已變更:請重新執行 @msg Image Trace finished, but the image or its settings changed meanwhile: trace it again 影像描圖已完成,但影像或其設定在此期間已變更:請重新描圖 @msg Image Trace finished, but its document was reverted: trace it again 影像描圖已完成,但其文件已回復:請重新描圖 diff --git a/crates/ui-egui/src/retype_runs.rs b/crates/ui-egui/src/retype_runs.rs index a4f819fc23..65d7027273 100644 --- a/crates/ui-egui/src/retype_runs.rs +++ b/crates/ui-egui/src/retype_runs.rs @@ -177,6 +177,8 @@ fn finish(app: &mut VectorcraftApp, r: Running, done: Option Date: Fri, 20 Nov 2026 03:22:36 -0800 Subject: [PATCH 013/151] Retype: grown font files and drawn glyphs count toward the search limits - A font file that grew past the limits after the installed fonts were listed counts as skipped, and the bytes read from it count toward the 2 GiB a search reads. A suitcase font's resource fork is read the same way, no further than one byte past the limit. - The 500,000-glyph budget counts the glyphs an index draws (each matched glyph once), not the face's mapped characters. - The Retype panel's background search hands the command the loaded fonts that match as well as the installed fonts it found, so a loaded font that matched stays listed after the fonts found are loaded. - A shape that no glyph's key fits (more than 48 contours) no longer keeps type.retype reading installed files after the other shapes have matched. --- crates/engine/src/cmd/retype_fonts.rs | 5 ++ crates/engine/src/cmd/retype_installed.rs | 31 ++++--- .../engine/src/cmd/retype_installed_tests.rs | 81 ++++++++++++++++++- crates/text/src/fontdb.rs | 2 +- crates/text/src/fontdb/installed.rs | 64 ++++++++++----- crates/text/src/lib.rs | 6 +- crates/text/src/retype.rs | 14 ++-- crates/text/src/suitcase.rs | 26 +++++- crates/text/src/tests/sysfonts.rs | 20 +++++ 9 files changed, 206 insertions(+), 43 deletions(-) diff --git a/crates/engine/src/cmd/retype_fonts.rs b/crates/engine/src/cmd/retype_fonts.rs index a9696e9ae8..6a351ef1b5 100644 --- a/crates/engine/src/cmd/retype_fonts.rs +++ b/crates/engine/src/cmd/retype_fonts.rs @@ -50,6 +50,11 @@ pub(super) struct Ranked { } impl Ranked { + /// The font. + pub(super) fn face(&self) -> &Arc { + &self.face + } + fn mean(&self) -> f64 { self.residual / self.matched.max(1) as f64 } diff --git a/crates/engine/src/cmd/retype_installed.rs b/crates/engine/src/cmd/retype_installed.rs index 9bb0e6113d..b74b60e81e 100644 --- a/crates/engine/src/cmd/retype_installed.rs +++ b/crates/engine/src/cmd/retype_installed.rs @@ -114,7 +114,8 @@ type File = (std::path::PathBuf, u64, Vec<(String, String)>); /// [`search`] within `limits`, keeping in its faces only those `listed` accepts. fn search_within(db: &FontDb, shapes: &[&BezPath], every: bool, limits: Limits, listed: &dyn Fn(&FontFace) -> bool) -> Result { let mut out = Installed::default(); - let shapes: Vec<&BezPath> = shapes.iter().copied().filter(|s| !is_plain(s)).collect(); + // A shape without a glyph's key matches no face: the search does not wait for it. + let shapes: Vec<&BezPath> = shapes.iter().copied().filter(|s| !is_plain(s) && shape_key(s).is_some()).collect(); let keys: BTreeSet = shapes.iter().filter_map(|s| shape_key(s)).collect(); if keys.is_empty() { return Ok(out); @@ -144,15 +145,15 @@ fn search_within(db: &FontDb, shapes: &[&BezPath], every: bool, limits: Limits, continue; } // A file that grew since the scan is read only within what is left. - let faces = db.read_unloaded_file(path, limits.file.min(bytes_left)); - // The bytes read: the file's fonts (a collection's faces share one), or its length then. - let mut datas: Vec<(usize, usize)> = faces.iter().map(|f| (f.file_data().as_ptr() as usize, f.file_data().len())).collect(); - datas.sort_unstable(); - datas.dedup(); - let read = datas.iter().map(|d| d.1 as u64).sum::().max(*len); - bytes_left = bytes_left.saturating_sub(read); + let file = db.read_unloaded_file(path, limits.file.min(bytes_left)); + // The bytes read, those of a file that grew past the limits too. + bytes_left = bytes_left.saturating_sub(file.bytes); + if file.too_long { + out.skipped += styles.len(); + continue; + } let wanted = |f: &FontFace| styles.iter().any(|(family, style)| f.family.eq_ignore_ascii_case(family) && f.style.eq_ignore_ascii_case(style)); - let faces: Vec> = faces.into_iter().filter(|f| wanted(f)).collect(); + let faces: Vec> = file.faces.into_iter().filter(|f| wanted(f)).collect(); for (j, face) in faces.iter().enumerate() { if out.faces.len() >= limits.faces { // The faces not compared past the cap: the rest of this file's and the later files'. @@ -391,7 +392,17 @@ impl RetypeSearch { fn run_in(&self, db: &FontDb) -> Result { let shapes: Vec<&BezPath> = self.shapes.iter().collect(); let installed = if self.command == "type.retypeFonts" { - super::fonts::rank_fonts(db, self.faces.clone(), &shapes, true, None)?.1 + let (ranked, mut found) = super::fonts::rank_fonts(db, self.faces.clone(), &shapes, true, None)?; + // The loaded faces that match are handed in too, ahead of the installed ones found: + // loading those can move a loaded face past the 96 the command lists. + let mut faces: Vec> = ranked.iter().map(|r| r.face().clone()).collect(); + for f in std::mem::take(&mut found.faces) { + if !faces.iter().any(|k| k.id() == f.id()) { + faces.push(f); + } + } + found.faces = faces; + found } else { let keys: BTreeSet = shapes.iter().filter_map(|sh| shape_key(sh)).collect(); let index = RetypeIndex::build(db, self.faces.iter().cloned(), &keys); diff --git a/crates/engine/src/cmd/retype_installed_tests.rs b/crates/engine/src/cmd/retype_installed_tests.rs index 0bea2c620c..9e8aaf96ae 100644 --- a/crates/engine/src/cmd/retype_installed_tests.rs +++ b/crates/engine/src/cmd/retype_installed_tests.rs @@ -98,7 +98,7 @@ fn a_loaded_face_of_the_same_names_counts_only_for_the_shapes_it_matches() { let dir = vectorcraft_testkit::temp_dir("retype-installed-twin"); let path = dir.join("RetypeTwin-Regular.ttf"); std::fs::write(&path, named_copy(false, names).unwrap()).unwrap(); - let read = db.read_unloaded_file(&path, u64::MAX).into_iter().next().unwrap(); + let read = db.read_unloaded_file(&path, u64::MAX).faces.into_iter().next().unwrap(); let shapes = glyphs(&db, "Rx"); let refs: Vec<&BezPath> = shapes.iter().collect(); let keys = keys(&shapes); @@ -140,6 +140,22 @@ fn plain_shapes_alone_read_no_installed_font() { assert_eq!(search(&db, &refs, false).unwrap().faces.len(), 1); } +#[test] +fn a_shape_without_a_glyph_s_key_does_not_keep_the_search_going() { + let (db, _) = installed("keyless", &["Retype Copy Keyless A", "Retype Copy Keyless B"]); + let mut shapes = glyphs(&db, "k"); + // More contours than any glyph's key counts: no face can match it. + let mut dots = BezPath::new(); + for i in 0..49 { + dots.extend(kurbo::Circle::new((10.0 * f64::from(i), 300.0), 3.0).path_elements(0.1)); + } + assert!(shape_key(&dots).is_none() && !vectorcraft_text::retype::is_plain(&dots)); + shapes.push(dots); + let refs: Vec<&BezPath> = shapes.iter().collect(); + let found = search(&db, &refs, false).unwrap(); + assert_eq!((found.read, found.faces.len()), (1, 1), "the second file is not read"); +} + #[test] fn the_search_stops_once_every_shape_matches_unless_every_face_is_wanted() { let (db, _) = installed("every", &["Retype Copy C", "Retype Copy D"]); @@ -180,6 +196,63 @@ fn faces_past_the_limits_are_skipped_and_counted() { assert_eq!((capped.read, capped.skipped, capped.faces.len()), (1, 2, 1)); } +#[test] +fn a_file_that_grows_past_the_limits_after_the_listing_is_skipped_and_its_bytes_count() { + let (db, mut files) = installed("grown", &["Retype Copy Y", "Retype Copy Z"]); + let shapes = glyphs(&db, "k"); + let refs: Vec<&BezPath> = shapes.iter().collect(); + // The order the search reads them in: smallest first. + let len = |p: &PathBuf| std::fs::metadata(p).unwrap().len(); + files.sort_by(|a, b| len(a).cmp(&len(b)).then_with(|| a.cmp(b))); + let (first, second) = (len(&files[0]), len(&files[1])); + let grown = files[0].clone(); + // The first file grows past the limit for one file as its reading starts, after the listing. + let sink: vectorcraft_doc::cancel::ProgressSink = std::rc::Rc::new(move |done, _, _| { + if done == 0 { + let mut data = std::fs::read(&grown).unwrap(); + data.resize(data.len() + second as usize + 1, 0); + std::fs::write(&grown, data).unwrap(); + } + }); + // Bytes for both files as listed: the grown file's reading takes one more than the limit for + // one file, which leaves too little for the second. + let limits = Limits { file: second, read: first + second, glyphs: usize::MAX, faces: usize::MAX }; + let token = vectorcraft_doc::cancel::CancelToken::new(); + let all = |_: &vectorcraft_text::FontFace| true; + let found = vectorcraft_doc::cancel::scope(&token, Some(sink), || search_within(&db, &refs, true, limits, &all)).unwrap(); + assert_eq!((found.read, found.skipped, found.faces.len()), (0, 2, 0)); +} + +#[test] +fn the_glyph_budget_counts_the_glyphs_drawn() { + let (db, files) = installed("glyph-budget", &["Retype Copy Budget"]); + let shapes = glyphs(&db, "k"); + let refs: Vec<&BezPath> = shapes.iter().collect(); + let face = db.read_unloaded_file(&files[0], u64::MAX).faces.into_iter().next().unwrap(); + let mapped = face.mapped_chars().len(); + let drawn = vectorcraft_text::retype::encoded_glyphs(&face); + assert!(drawn < mapped, "{drawn} of {mapped}"); + // A budget below the face's characters and at the glyphs drawn: the face is compared. + let open = Limits { file: u64::MAX, read: u64::MAX, glyphs: drawn, faces: usize::MAX }; + let found = search_within(&db, &refs, true, open, &|_| true).unwrap(); + assert_eq!((found.read, found.skipped, found.faces.len()), (1, 0, 1)); +} + +#[test] +fn a_run_away_from_the_list_hands_in_the_loaded_faces_that_match_with_the_installed_ones() { + let (db, _) = installed("list-run", &["Retype Copy List"]); + db.add_font( + vectorcraft_text::test_fonts::named_copy(false, ("Retype Loaded List", "Regular", "Version 1.000", "RetypeLoadedList-Regular")).unwrap(), + ); + let loaded: Vec<_> = db.loaded_faces().into_iter().filter(|f| f.family == "Retype Loaded List").collect(); + let search = super::RetypeSearch { command: "type.retypeFonts", doc: 1, shapes: glyphs(&db, "Rx"), faces: loaded.clone() }; + let found = search.run_in(&db).unwrap(); + let families: Vec<&str> = found.installed.faces.iter().map(|f| f.family.as_str()).collect(); + // The loaded face first, then the installed one, each once. + assert_eq!(families, ["Retype Loaded List", "Retype Copy List"]); + assert_eq!((found.installed.read, found.installed.skipped), (1, 0)); +} + #[test] fn faces_a_list_turns_down_are_loaded_and_take_no_place() { let (db, _) = installed("listed", &["Retype Copy R", "Retype Copy S", "Retype Copy T"]); @@ -244,7 +317,11 @@ fn a_run_away_from_the_command_loads_the_faces_it_finds() { assert!(run.current(&s)); let found = run.run_in(&db).unwrap(); assert_eq!(found.json(), json!({"read": 1, "skipped": 0})); - assert_eq!(found.installed.faces.iter().map(|f| f.family.as_str()).collect::>(), ["Retype Copy X"]); + // The loaded faces that match are handed in with it, ahead of it. + let families: Vec<&str> = found.installed.faces.iter().map(|f| f.family.as_str()).collect(); + assert_eq!(families.last(), Some(&"Retype Copy X"), "{families:?}"); + assert_eq!(families.iter().filter(|f| **f == "Retype Copy X").count(), 1, "{families:?}"); + assert!(families.contains(&"Source Sans 3"), "{families:?}"); assert!(!unloaded(&db, "Retype Copy X")); // A change of selection or content: it no longer applies. s.execute("select.set", &json!({"ids": [ids[0]]})).unwrap(); diff --git a/crates/text/src/fontdb.rs b/crates/text/src/fontdb.rs index 4008705a5f..59ee489fb0 100644 --- a/crates/text/src/fontdb.rs +++ b/crates/text/src/fontdb.rs @@ -60,7 +60,7 @@ pub(crate) use face::PathAlignHeights; pub use face::{FALLBACK_FAMILY, FontFace, IcfMargins, OutlineFormat}; pub(crate) use glyph_pen::FlipPen; pub use gsub::{GlyphCategory, GlyphCategoryKind, GlyphOrigin, JoiningPosition, Substitution, SubstitutionKind}; -pub use installed::InstalledFace; +pub use installed::{InstalledFace, UnloadedFile}; #[cfg(not(target_arch = "wasm32"))] use names::SysFallback; #[cfg(test)] diff --git a/crates/text/src/fontdb/installed.rs b/crates/text/src/fontdb/installed.rs index fd0fff2382..3a9a1946bd 100644 --- a/crates/text/src/fontdb/installed.rs +++ b/crates/text/src/fontdb/installed.rs @@ -54,39 +54,55 @@ impl FontDb { } /// The faces in the font file at `path` (a suitcase font's in its resource fork), read for one - /// search and not added to the database: none when the file, or the fork, is longer than - /// `max_len` bytes or holds no font. Each face read has an id of its own, which no loaded face - /// has, and its path is `path`. Empty on wasm. - pub fn read_unloaded_file(&self, path: &Path, max_len: u64) -> Vec> { + /// search and not added to the database, with the bytes read: no faces when the file, or the + /// fork, is longer than `max_len` bytes ([`UnloadedFile::too_long`]) or holds no font. Each face + /// read has an id of its own, which no loaded face has, and its path is `path`. Empty on wasm. + pub fn read_unloaded_file(&self, path: &Path, max_len: u64) -> UnloadedFile { #[cfg(not(target_arch = "wasm32"))] { - let files = if crate::suitcase::is_suitcase(path) { - if crate::suitcase::fork_len(path) > max_len { - return vec![]; + let (files, bytes) = if crate::suitcase::is_suitcase(path) { + match crate::suitcase::read_fonts_within(path, max_len) { + (_, n, true) => return UnloadedFile { bytes: n, too_long: true, ..Default::default() }, + (fonts, n, false) => (fonts, n), } - crate::suitcase::read_fonts(path) } else { - read_within(path, max_len).into_iter().collect() + match read_within(path, max_len) { + Some((data, n)) if n <= max_len => (vec![data], n), + Some((_, n)) => return UnloadedFile { bytes: n, too_long: true, ..Default::default() }, + None => return UnloadedFile::default(), + } }; - let mut out = vec![]; + let mut faces = vec![]; for data in files { let data = Arc::new(data); for (i, spec) in enumerate_faces(&data) { if let Some(f) = make_face(FontBytes::Owned(data.clone()), i, spec, Some(path.to_path_buf())) { - out.push(Arc::new(f)); + faces.push(Arc::new(f)); } } } - out + UnloadedFile { faces, bytes, too_long: false } } #[cfg(target_arch = "wasm32")] { let _ = (path, max_len); - vec![] + UnloadedFile::default() } } } +/// What [`FontDb::read_unloaded_file`] read from one font file. +#[derive(Default)] +pub struct UnloadedFile { + /// The faces read, not loaded. + pub faces: Vec>, + /// The bytes read from the file, those of a file longer than the limit included (at most one + /// past it). + pub bytes: u64, + /// The file, or the fork, is longer than the limit: no face was read. + pub too_long: bool, +} + impl FontDb { /// Load `face`, a face [`Self::read_unloaded_file`] read, without reading its file again or /// the family's other files: it joins the loaded faces, unless a face of its family, style and @@ -116,13 +132,15 @@ fn file_len(path: &Path) -> u64 { } } -/// The file at `path`, when it is at most `max_len` bytes long (read no further than one byte past). +/// The file at `path`, read no further than one byte past `max_len`, with the bytes read: more than +/// `max_len` when the file is longer. None when it cannot be read. #[cfg(not(target_arch = "wasm32"))] -fn read_within(path: &Path, max_len: u64) -> Option> { +fn read_within(path: &Path, max_len: u64) -> Option<(Vec, u64)> { use std::io::Read; let mut data = Vec::new(); std::fs::File::open(path).ok()?.take(max_len.saturating_add(1)).read_to_end(&mut data).ok()?; - (data.len() as u64 <= max_len).then_some(data) + let n = data.len() as u64; + Some((data, n)) } #[cfg(test)] @@ -150,16 +168,22 @@ mod tests { let regular = inter.iter().find(|f| f.style == "Regular").unwrap(); assert_eq!(regular.len, std::fs::metadata(®ular.path).unwrap().len()); let before = db.loaded_faces().len(); - let read = db.read_unloaded_file(®ular.path, regular.len); + let file = db.read_unloaded_file(®ular.path, regular.len); + assert_eq!((file.bytes, file.too_long), (regular.len, false)); + let read = file.faces; assert!(read.iter().any(|f| f.family == "Inter" && f.style == "Regular"), "the file's face is read"); assert!(read.iter().all(|f| f.path() == Some(regular.path.as_path()))); // Read for the search only: the database does not hold it, and no loaded face has its id. assert_eq!(db.loaded_faces().len(), before); assert!(read.iter().all(|f| db.face_by_id(f.id()).is_none())); assert!(db.unloaded_installed_faces().iter().any(|f| f.family == "Inter"), "still not loaded"); - // A file longer than the limit is not read. - assert!(db.read_unloaded_file(®ular.path, regular.len - 1).is_empty()); - assert!(db.read_unloaded_file(®ular.path.with_extension("missing"), u64::MAX).is_empty()); + // A file longer than the limit is not read past one byte over it, and says so. + let long = db.read_unloaded_file(®ular.path, regular.len - 1); + assert!(long.faces.is_empty()); + assert_eq!((long.bytes, long.too_long), (regular.len, true)); + let missing = db.read_unloaded_file(®ular.path.with_extension("missing"), u64::MAX); + assert!(missing.faces.is_empty()); + assert_eq!((missing.bytes, missing.too_long), (0, false)); // Once loaded, the family is no longer listed. assert!(db.face("Inter", "Regular").is_some_and(|f| f.family == "Inter")); assert!(!db.unloaded_installed_faces().iter().any(|f| f.family == "Inter" && f.style == "Regular")); diff --git a/crates/text/src/lib.rs b/crates/text/src/lib.rs index bddb446484..f4f7c8543f 100644 --- a/crates/text/src/lib.rs +++ b/crates/text/src/lib.rs @@ -44,9 +44,9 @@ pub use features::{ pub use fontdb::{ CompositeCoverage, FALLBACK_FAMILY, FontClass, FontDb, FontFace, FontLikeness, FontMatch, FontTraits, GENERIC_FAMILIES, GlyphAlternate, GlyphCategory, GlyphCategoryKind, GlyphOrigin, IcfMargins, InstalledFace, JoiningPosition, LentCompositeFonts, OutlineFormat, PlatformFontFiles, - RECENTLY_ADDED_WITHIN, RecentlyAdded, StylisticSet, Substitution, SubstitutionKind, WantedFont, WantedFonts, app_font_dir, is_font_file, - is_generic_family, is_suitcase, set_app_font_dir, set_platform_font_files, set_user_font_dirs, set_user_font_dirs_confined, style_weight, - system_font_dirs, user_font_dirs, + RECENTLY_ADDED_WITHIN, RecentlyAdded, StylisticSet, Substitution, SubstitutionKind, UnloadedFile, WantedFont, WantedFonts, app_font_dir, + is_font_file, is_generic_family, is_suitcase, set_app_font_dir, set_platform_font_files, set_user_font_dirs, set_user_font_dirs_confined, + style_weight, system_font_dirs, user_font_dirs, }; pub use hyphen::{hyphenation_exceptions, set_hyphenation_exceptions}; pub use layout::{envelope_ink, layout_inputs, register_envelope_ink}; diff --git a/crates/text/src/retype.rs b/crates/text/src/retype.rs index 901403f341..5f1a08ba03 100644 --- a/crates/text/src/retype.rs +++ b/crates/text/src/retype.rs @@ -355,10 +355,10 @@ fn matched_glyphs(face: &FontFace) -> Vec<(u32, char)> { gids } -/// How many glyphs of `face` an index draws to read their keys: at most [`MAX_GLYPHS_PER_FACE`]. -/// Reads the face's cmap only. +/// How many glyphs of `face` an index draws to read their keys: the glyphs it matches, each once, +/// at most [`MAX_GLYPHS_PER_FACE`]. Reads the face's cmap only. pub fn encoded_glyphs(face: &FontFace) -> usize { - face.mapped_chars().len().min(MAX_GLYPHS_PER_FACE) + matched_glyphs(face).len() } /// [`FaceKeys`] of `face`, each matched glyph drawn once, past the outline cache. @@ -1026,17 +1026,19 @@ mod tests { } /// A face read from an installed file and not loaded is indexed as a loaded one is, and the - /// count of glyphs its index draws comes from its cmap. + /// count of glyphs its index draws comes from its cmap: the glyphs it matches, each once. #[cfg(not(target_arch = "wasm32"))] #[test] fn an_unloaded_face_is_indexed_as_a_loaded_one() { let dir = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../assets/fonts"); let db = FontDb::with_font_dirs(vec![]); let loaded = db.face("Source Sans 3", "Regular").unwrap(); - let read = db.read_unloaded_file(&dir.join("SourceSans3-Regular.ttf"), u64::MAX); + let read = db.read_unloaded_file(&dir.join("SourceSans3-Regular.ttf"), u64::MAX).faces; let face = read.into_iter().find(|f| f.family == "Source Sans 3").unwrap(); assert_ne!(face.id(), loaded.id()); - assert_eq!(encoded_glyphs(&face), face.mapped_chars().len().min(MAX_GLYPHS_PER_FACE)); + assert_eq!(encoded_glyphs(&face), matched_glyphs(&face).len()); + // Spaces, controls and shape symbols are not drawn, nor one glyph twice for two characters. + assert!(encoded_glyphs(&face) < face.mapped_chars().len().min(MAX_GLYPHS_PER_FACE)); let shape = Affine::translate((40.0, 90.0)) * Affine::scale(0.03) * db.outline_uncached(&face, face.glyph_for('g')); let keys: BTreeSet = std::iter::once(shape_key(&shape).unwrap()).collect(); let unloaded = RetypeIndex::build_unloaded(&db, face.clone(), &keys); diff --git a/crates/text/src/suitcase.rs b/crates/text/src/suitcase.rs index ff06a66672..102492b252 100644 --- a/crates/text/src/suitcase.rs +++ b/crates/text/src/suitcase.rs @@ -65,6 +65,19 @@ pub(crate) fn read_fonts(path: &Path) -> Vec> { sfnt_resources(&fork).into_iter().map(<[u8]>::to_vec).collect() } +/// [`read_fonts`] reading the fork no further than one byte past `max_len` (at most the longest +/// fork read), with the bytes read: no fonts, and true, when the fork is longer. +#[cfg(not(target_arch = "wasm32"))] +pub(crate) fn read_fonts_within(path: &Path, max_len: u64) -> (Vec>, u64, bool) { + let max_len = max_len.min(MAX_FORK); + let Some(fork) = read_fork_within(path, max_len.saturating_add(1)) else { return (vec![], 0, false) }; + let n = fork.len() as u64; + if n > max_len { + return (vec![], n, true); + } + (sfnt_resources(&fork).into_iter().map(<[u8]>::to_vec).collect(), n, false) +} + /// Whether the file at `path` is a suitcase font: nothing in its data fork and something in its /// resource fork. pub(crate) fn is_suitcase(path: &Path) -> bool { @@ -84,9 +97,15 @@ pub(crate) fn fork_len(path: &Path) -> u64 { #[cfg(target_os = "macos")] fn read_fork(path: &Path) -> Option> { + read_fork_within(path, MAX_FORK) +} + +/// The first `max` bytes of the resource fork of the file at `path`. +#[cfg(target_os = "macos")] +fn read_fork_within(path: &Path, max: u64) -> Option> { use std::io::Read; let mut fork = Vec::new(); - std::fs::File::open(fork_path(path)).ok()?.take(MAX_FORK).read_to_end(&mut fork).ok()?; + std::fs::File::open(fork_path(path)).ok()?.take(max).read_to_end(&mut fork).ok()?; Some(fork) } @@ -101,6 +120,11 @@ fn read_fork(_: &Path) -> Option> { None } +#[cfg(all(not(target_os = "macos"), not(target_arch = "wasm32")))] +fn read_fork_within(_: &Path, _: u64) -> Option> { + None +} + /// A resource fork holding `fonts` as `sfnt` resources and one other resource (a `vers`), as /// a font utility writes them. #[cfg(test)] diff --git a/crates/text/src/tests/sysfonts.rs b/crates/text/src/tests/sysfonts.rs index ada5c45dd1..9b43a908c9 100644 --- a/crates/text/src/tests/sysfonts.rs +++ b/crates/text/src/tests/sysfonts.rs @@ -800,6 +800,26 @@ fn a_search_reads_a_suitcase_font_only_within_its_share() { let _ = std::fs::remove_dir_all(&dir); } +/// A suitcase font read for one search (Retype) is read no further than one byte past the limit, +/// and the bytes read are counted. +#[cfg(target_os = "macos")] +#[test] +fn a_suitcase_font_read_for_a_search_counts_the_bytes_of_its_fork() { + let dir = std::env::temp_dir().join(format!("vc-sysfonts-{}-unloaded-suitcase", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let suitcase = dir.join("Sysfont Sans3"); + std::fs::write(&suitcase, b"").unwrap(); + let fork = crate::suitcase::fork_of(&[renamed("SourceSans3-Regular.ttf")]); + let len = fork.len() as u64; + std::fs::write(suitcase.join("..namedfork/rsrc"), &fork).unwrap(); + let db = FontDb::with_font_dirs(vec![]); + let file = db.read_unloaded_file(&suitcase, len); + assert_eq!((file.faces.len(), file.bytes, file.too_long), (1, len, false)); + let long = db.read_unloaded_file(&suitcase, len - 1); + assert_eq!((long.faces.len(), long.bytes, long.too_long), (0, len, true)); + let _ = std::fs::remove_dir_all(&dir); +} + #[test] fn font_files_are_told_by_their_extension() { for name in ["a/B.TTF", "c.otf", "d.Ttc", "e.otc"] { From 5dda1d544068135c13dd7a062a282d167606fc04 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 20 Nov 2026 07:01:26 -0800 Subject: [PATCH 014/151] MCP: regenerate the UI command catalog for Retype's installed-font search `cargo xtask ui-commands` writes the new `installed` parameter of retype.find and the new retype.cancelSearch row into crates/mcp/src/ui_catalog.rs, so `cargo xtask ui-commands --check` passes again. --- crates/mcp/src/ui_catalog.rs | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/crates/mcp/src/ui_catalog.rs b/crates/mcp/src/ui_catalog.rs index 359f41676b..16e86a7037 100644 --- a/crates/mcp/src/ui_catalog.rs +++ b/crates/mcp/src/ui_catalog.rs @@ -868,7 +868,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "retype.find", "Find Matching Fonts", "", - "{more?: bool} show the Retype panel and list the fonts whose glyphs match the selected outlined text, compared and ranked as type.retypeFonts does (up to 96 loaded fonts, those of the document's live type first): ten, as Find Matching Fonts does (more false, omitted or null: a new search), or with more: true the next five fonts the last search found (whatever is selected now; before any search, a first search), as Find more font matches does; the document does not change; a search with no path or compound path selected, or a more other than true, false or null, is an error and leaves the list as it was; returns what retype.list returns", + "{more?: bool, installed?: bool} show the Retype panel and list the fonts whose glyphs match the selected outlined text, compared and ranked as type.retypeFonts does (up to 96 loaded fonts, those of the document's live type first, then, unless installed is false, the installed fonts not loaded yet, which the app reads in the background, with retype.cancelSearch to stop it, when the panel's button, a menu or the command palette runs it): ten, as Find Matching Fonts does (more false, omitted or null: a new search), or with more: true the next five fonts the last search found (whatever is selected now; before any search, a first search), as Find more font matches does; the document does not change; a search with no path or compound path selected, or a more or installed other than true, false or null, is an error and leaves the list as it was; returns what retype.list returns", ), ( "retype.list", @@ -2025,6 +2025,12 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "", "{} close the progress window of the Image Traces running in the background; they go on, shown in the status bar → {hidden: n}", ), + ( + "retype.cancelSearch", + "Cancel Font Search", + "", + "{} stop the search of the installed fonts that Type › Retype or the Retype panel's Find Matching Fonts runs in the background (its progress window's Cancel): it stops before its next file, and Retype changes nothing and the list stays as it was → {cancelled: n}", + ), ( "ui.runScript", "Other Script…", From 830cf56430fddc670e1f19c8e6527f24f73d4ec8 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 20 Nov 2026 15:18:38 -0800 Subject: [PATCH 015/151] Save for Web: Save Color Table and Load Color Table write and read .act files MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The color table's menu gains Save Color Table… and Load Color Table…, as the help page describes (https://help.adobe.com/archive/en_US/illustrator/cs4/illustrator_cs4_help.pdf#page=404). - document.exportForWeb.saveColorTable writes the GIF or PNG-8 table the preview shows as a color table file in the published layout (https://www.adobe.com/devnet-apps/photoshop/fileformatashtml/): 256 RGB entries in file order, zero-padded, then the color count and the transparent index, two bytes each, big-endian (65535 for none). It always writes 772 bytes and writes shifted colors as written. - webExport.loadColorTable reads the 768-byte and 772-byte forms and returns the settings with the file's colors, other than the transparent entry, as the fixed Custom palette and Colors set to the file's count. The table's other edits and its sort are cleared and Web Snap is set to 0, so the loaded colors are written as they are. It reads at most 773 bytes, rejects other sizes, counts of 0 or above 256, both or neither of path and dataBase64, and JPEG or PNG-24, and remembers nothing. Load Color Table… is disabled on the web. - document.exportForWeb.preview rejects a slice that is not a whole number from 1 up instead of ignoring it. Docs: docs/mcp.md, docs/target-app-parity.md. --- crates/engine/src/cmd/params.rs | 2 + crates/engine/src/cmd/webexport.rs | 217 ++++++++++++++++-- crates/engine/src/tests/webexport.rs | 191 +++++++++++++++ crates/ui-egui/src/dialogs/save_for_web.rs | 66 +++++- .../ui-egui/src/dialogs/tests_save_for_web.rs | 47 ++++ crates/ui-egui/src/i18n/bg.tsv | 4 + crates/ui-egui/src/i18n/bs.tsv | 4 + crates/ui-egui/src/i18n/ca.tsv | 8 + crates/ui-egui/src/i18n/cs.tsv | 8 + crates/ui-egui/src/i18n/da.tsv | 8 + crates/ui-egui/src/i18n/de.tsv | 8 + crates/ui-egui/src/i18n/el.tsv | 8 + crates/ui-egui/src/i18n/es.tsv | 8 + crates/ui-egui/src/i18n/fi.tsv | 8 + crates/ui-egui/src/i18n/fr.tsv | 8 + crates/ui-egui/src/i18n/gu.tsv | 4 + crates/ui-egui/src/i18n/hi.tsv | 8 + crates/ui-egui/src/i18n/hu.tsv | 8 + crates/ui-egui/src/i18n/id.tsv | 8 + crates/ui-egui/src/i18n/it.tsv | 8 + crates/ui-egui/src/i18n/ja.tsv | 8 + crates/ui-egui/src/i18n/ka.tsv | 8 + crates/ui-egui/src/i18n/ko.tsv | 8 + crates/ui-egui/src/i18n/nl.tsv | 8 + crates/ui-egui/src/i18n/pl.tsv | 8 + crates/ui-egui/src/i18n/pt-br.tsv | 8 + crates/ui-egui/src/i18n/ru.tsv | 8 + crates/ui-egui/src/i18n/sv.tsv | 8 + crates/ui-egui/src/i18n/tr.tsv | 8 + crates/ui-egui/src/i18n/uk.tsv | 8 + crates/ui-egui/src/i18n/vi.tsv | 8 + crates/ui-egui/src/i18n/zh-hans.tsv | 8 + crates/ui-egui/src/i18n/zh-hant.tsv | 8 + crates/ui-egui/src/io/save.rs | 1 + docs/mcp.md | 26 ++- docs/target-app-parity.md | 1 + 36 files changed, 735 insertions(+), 28 deletions(-) diff --git a/crates/engine/src/cmd/params.rs b/crates/engine/src/cmd/params.rs index 64ce29e337..ea2c3568a1 100644 --- a/crates/engine/src/cmd/params.rs +++ b/crates/engine/src/cmd/params.rs @@ -698,6 +698,7 @@ pub const UNCHECKED: &[&str] = &[ "document.exportForScreens", "document.exportForWeb", "document.exportForWeb.preview", + "document.exportForWeb.saveColorTable", "document.exportPdf", "document.find", "document.inspect", @@ -803,6 +804,7 @@ pub const UNCHECKED: &[&str] = &[ "transparency.setOpacityMask", "transparency.unlinkOpacityMask", "type.pathOptions", + "webExport.loadColorTable", "webExport.optimizeToFileSize", "webExport.presets.save", "webExport.settings", diff --git a/crates/engine/src/cmd/webexport.rs b/crates/engine/src/cmd/webexport.rs index 498982a7f9..0f77411cd8 100644 --- a/crates/engine/src/cmd/webexport.rs +++ b/crates/engine/src/cmd/webexport.rs @@ -21,7 +21,7 @@ use vectorcraft_render::encode::quantize::{self, Dither, Indexed, PaletteOptions use vectorcraft_render::encode::web::{self, ColorSort}; use vectorcraft_render::encode::{gif, jpeg, png}; -use super::{CommandSpec, Result, Session, always, bad, bool_or, cmd, f64_or, has_doc, str_param, unique_name_from}; +use super::{CommandSpec, Result, Session, always, bad, bool_or, cmd, f64_or, has_doc, str_param, text_param, unique_name_from}; const C: &str = "document.exportForWeb"; @@ -45,6 +45,24 @@ pub fn specs() -> Vec { has_doc, preview ), + cmd!( + "document.exportForWeb.saveColorTable", + "Save Color Table", + [], + None, + "{path?: the .act file (.act is added to a name without an extension), …the settings of document.exportForWeb (preset?, format?: gif|png8…), slice?: n (1-based, from slice.list; default the whole image)} write the GIF or PNG-8 color table the preview shows as a color table file: 772 bytes, the colors as written (red, green, blue) in file order, zero bytes up to 256 colors, then the number of colors and the transparent entry's index (65535 for none), two bytes each, most significant byte first → {path, colors (how many), transparentIndex (null for none), bytes, warnings}; no path → {dataBase64, colors, transparentIndex, bytes, warnings}. jpg and png24 are an error; the document and the settings do not change", + has_doc, + save_color_table + ), + cmd!( + query "webExport.loadColorTable", + "Load Color Table", + [], + None, + "{path | dataBase64: a color table file (.act: 768 bytes of 256 colors, or 772 bytes with the number of colors used, 1–256, and the transparent entry's index), …the settings of document.exportForWeb (preset?, format?: gif|png8…)} the settings with the table loaded: its colors other than the transparent entry become colorTable.customPalette, colors becomes the number of colors it uses (at least 2), the table's other edits (locked, transparent, deleted, shifted, webShift and sort) are cleared and webSnap becomes 0 →{colors: [\"#rrggbb\"…] (the colors it uses, in file order), transparentIndex (null for none; an index past the colors used names none), settings}. Give exactly one of path and dataBase64; another file size, a count of 0 or above 256, jpg and png24 are errors; nothing is remembered", + always, + load_color_table + ), cmd!( query "webExport.optimizeToFileSize", "Optimize to File Size", @@ -1196,24 +1214,7 @@ fn preview(s: &mut Session, p: &Value) -> Result { if !(kbps.is_finite() && kbps > 0.0) { return Err(bad(P, format!("kbps must be a positive number, not {kbps}"))); } - let st = s.doc()?; - let doc = &st.doc; - let failed = vectorcraft_render::decode_failures(); - let r = render(doc, &settings).map_err(|e| bad(P, e))?; - let warnings = undecoded(failed); - let areas = doc.slice_layout(); - let selected = super::slices::selected_slices(doc, &st.selection); - let cells = cells(&areas, &selected, &settings, &r).map_err(|e| bad(P, e))?; - let images = cells.iter().filter(|c| c.area.id.and_then(|id| doc.slice_options(id)).is_none_or(|o| o.kind == SliceKind::Image)).count().max(1); - let o = match p.get("slice").and_then(Value::as_u64) { - Some(n) => { - let c = cells.iter().find(|c| c.area.number as u64 == n).ok_or_else(|| bad(P, format!("no slice {n} in the image (see slice.list)")))?; - let [x0, y0, x1, y1] = c.px; - optimize(doc, &crop(&r, c.px), x1 - x0, y1 - y0, &settings) - } - None => optimize(doc, &r.rgba, r.width, r.height, &settings), - } - .map_err(|e| bad(P, e))?; + let Shown { o, images, warnings } = shown(s, &settings, p, P)?; let mut out = json!({ "format": settings.format.id(), "width": o.width, "height": o.height, "bytes": o.bytes.len(), "seconds": download_seconds(o.bytes.len(), kbps), "kbps": kbps, "slices": images, "warnings": warnings, @@ -1237,6 +1238,184 @@ fn preview(s: &mut Session, p: &Value) -> Result { Ok(out) } +/// The file Save writes with some settings, as the preview shows it. +struct Shown { + o: Optimized, + /// The images an export writes. + images: usize, + /// The export's warnings. + warnings: Vec<&'static str>, +} + +/// What Save writes with `settings` for the whole image, or for the slice `p.slice` names (1-based, +/// from `slice.list`), for the command `cmd`. A `slice` that is not a whole number from 1 up is an +/// error. +fn shown(s: &mut Session, settings: &WebSettings, p: &Value, cmd: &str) -> Result { + let slice = match p.get("slice") { + None | Some(Value::Null) => None, + Some(v) => Some(v.as_u64().filter(|n| *n >= 1).ok_or_else(|| bad(cmd, "`slice` is a slice number from `slice.list`"))?), + }; + let st = s.doc()?; + let doc = &st.doc; + let failed = vectorcraft_render::decode_failures(); + let r = render(doc, settings).map_err(|e| bad(cmd, e))?; + let warnings = undecoded(failed); + let areas = doc.slice_layout(); + let selected = super::slices::selected_slices(doc, &st.selection); + let cells = cells(&areas, &selected, settings, &r).map_err(|e| bad(cmd, e))?; + let images = cells.iter().filter(|c| c.area.id.and_then(|id| doc.slice_options(id)).is_none_or(|o| o.kind == SliceKind::Image)).count().max(1); + let o = match slice { + Some(n) => { + let c = + cells.iter().find(|c| c.area.number as u64 == n).ok_or_else(|| bad(cmd, format!("no slice {n} in the image (see slice.list)")))?; + let [x0, y0, x1, y1] = c.px; + optimize(doc, &crop(&r, c.px), x1 - x0, y1 - y0, settings) + } + None => optimize(doc, &r.rgba, r.width, r.height, settings), + } + .map_err(|e| bad(cmd, e))?; + Ok(Shown { o, images, warnings }) +} + +// ---------- color table files ---------- + +/// The extension of a color table file. +pub const COLOR_TABLE_EXT: &str = "act"; +/// The size of a color table file with its color count and transparent entry: 256 RGB triples +/// (768 bytes), then the two numbers, each two bytes, most significant byte first. +pub const ACT_LEN: usize = 772; +/// The size of a color table file of 256 RGB triples alone. +const ACT_COLORS_LEN: usize = 768; +/// The transparent entry of a color table file that has none. +const ACT_NO_TRANSPARENT: u16 = 0xFFFF; + +/// The error for bytes that are not a color table file. +const NOT_A_TABLE: &str = "not a color table: an .act file is 768 or 772 bytes long and uses 1 to 256 colors"; + +/// A color table file (`.act`) of `colors`, a palette format's color table in file order: each +/// color as written, red, green and blue, one byte each; zero bytes up to 256 colors; the number +/// of colors and the index of the transparent entry (`0xFFFF` for none), two bytes each, most +/// significant byte first. Colors past the 256th are left out. +pub fn act_bytes(colors: &[TableColor]) -> Vec { + let colors = &colors[..colors.len().min(256)]; + let mut out = vec![0u8; ACT_LEN]; + for (slot, c) in out.as_chunks_mut::<3>().0.iter_mut().zip(colors) { + *slot = c.color; + } + // At most 256 colors: both numbers fit in two bytes. + let count = colors.len() as u16; + let transparent = colors.iter().position(|c| c.transparent).map_or(ACT_NO_TRANSPARENT, |i| i as u16); + out[ACT_COLORS_LEN..ACT_COLORS_LEN + 2].copy_from_slice(&count.to_be_bytes()); + out[ACT_COLORS_LEN + 2..].copy_from_slice(&transparent.to_be_bytes()); + out +} + +/// The colors of a color table file and its transparent entry. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct ActTable { + /// The colors the file uses, in its order. + pub colors: Vec<[u8; 3]>, + /// The index of the transparent entry, when the file names one of `colors`. + pub transparent: Option, +} + +/// Read a color table file: 768 bytes are 256 colors; 772 bytes add the number of colors used +/// (1 to 256) and the transparent entry's index. A transparent index past the colors used names +/// no entry. Any other size, or a count of 0 or above 256, is an error. +pub fn read_act(bytes: &[u8]) -> std::result::Result { + let (count, transparent) = match bytes.len() { + ACT_COLORS_LEN => (256, None), + ACT_LEN => { + let at = |i: usize| usize::from(u16::from_be_bytes([bytes[i], bytes[i + 1]])); + (at(ACT_COLORS_LEN), Some(at(ACT_COLORS_LEN + 2))) + } + _ => return Err(NOT_A_TABLE.into()), + }; + if !(1..=256).contains(&count) { + return Err(NOT_A_TABLE.into()); + } + let colors: Vec<[u8; 3]> = bytes[..count * 3].as_chunks::<3>().0.to_vec(); + Ok(ActTable { colors, transparent: transparent.filter(|i| *i < count) }) +} + +/// `settings` with the color table `t` loaded: its colors other than the transparent entry become +/// the fixed palette (`colorTable.customPalette`), and `colors` becomes the number of colors the +/// file uses (at least 2). The table's other edits (locked, transparent, deleted, shifted and +/// web-shifted colors, and its sort) are cleared and Web Snap is set to 0, so every loaded color is +/// written as it is, in the file's order. A table whose only color is its transparent entry loads +/// that color. +pub fn with_table(settings: &WebSettings, t: &ActTable) -> WebSettings { + let mut s = settings.clone(); + let mut palette: Vec = t.colors.iter().enumerate().filter(|(i, _)| Some(*i) != t.transparent).map(|(_, c)| hex(*c)).collect(); + if palette.is_empty() { + palette = t.colors.iter().map(|c| hex(*c)).collect(); + } + s.colors = (t.colors.len() as u16).clamp(2, 256); + s.web_snap = 0; + s.color_table = ColorTable { custom_palette: palette, ..ColorTable::default() }; + s +} + +/// `cmd`'s error for a format without a color table. +fn no_table(cmd: &str, f: WebFormat) -> super::EngineError { + let format = f.id(); + bad(cmd, format!("`{format}` has no color table: use gif or png8")) +} + +fn save_color_table(s: &mut Session, p: &Value) -> Result { + const P: &str = "document.exportForWeb.saveColorTable"; + let settings = s.web_settings(p).map_err(|e| bad(P, e))?; + if !settings.format.palette() { + return Err(no_table(P, settings.format)); + } + let path = text_param(p, "path", P)? + .filter(|p| !p.trim().is_empty()) + .map(|p| if std::path::Path::new(p).extension().is_none() { format!("{p}.{COLOR_TABLE_EXT}") } else { p.to_string() }); + let Shown { o, warnings, .. } = shown(s, &settings, p, P)?; + let bytes = act_bytes(&o.colors); + let mut out = json!({ + "colors": o.colors.len().min(256), + "transparentIndex": o.colors.iter().position(|c| c.transparent), + "bytes": bytes.len(), + "warnings": warnings, + }); + match path { + Some(path) => { + super::fileio::write_file(&path, &bytes)?; + out["path"] = json!(path); + } + None => out["dataBase64"] = json!(vectorcraft_format::base64_encode(&bytes)), + } + Ok(out) +} + +fn load_color_table(s: &mut Session, p: &Value) -> Result { + const L: &str = "webExport.loadColorTable"; + let settings = s.web_settings(p).map_err(|e| bad(L, e))?; + if !settings.format.palette() { + return Err(no_table(L, settings.format)); + } + // One byte more than a color table shows a file that is too long. + let bytes = match (text_param(p, "path", L)?, text_param(p, "dataBase64", L)?) { + (Some(path), None) => super::fileio::read_file_head(path, ACT_LEN + 1)?, + (None, Some(b64)) => { + // Text past the base64 of the longest table makes the file too long. + if b64.bytes().filter(|b| !b.is_ascii_whitespace()).count() > ACT_LEN.div_ceil(3) * 4 { + return Err(bad(L, NOT_A_TABLE)); + } + super::scripts::decode_head(b64, ACT_LEN + 1).ok_or_else(|| bad(L, "bad dataBase64"))? + } + _ => return Err(bad(L, "give exactly one of `path` and `dataBase64`")), + }; + let t = read_act(&bytes).map_err(|e| bad(L, e))?; + let loaded = with_table(&settings, &t); + Ok(json!({ + "colors": t.colors.iter().map(|c| hex(*c)).collect::>(), + "transparentIndex": t.transparent, + "settings": loaded.to_json(), + })) +} + // ---------- Optimize to File Size ---------- /// The most trial settings `webExport.optimizeToFileSize` encodes. Each trial encodes every image diff --git a/crates/engine/src/tests/webexport.rs b/crates/engine/src/tests/webexport.rs index fe3deecbef..150ea1f67a 100644 --- a/crates/engine/src/tests/webexport.rs +++ b/crates/engine/src/tests/webexport.rs @@ -1011,3 +1011,194 @@ fn optimize_to_file_size_finds_a_fit_when_a_lower_setting_gives_a_larger_file() assert!(highest_within(&mut size, &start, (1, 90), set_quality, 100, &mut smallest).unwrap().is_none()); assert_eq!(smallest.map(|(s, n)| (s.quality, n)), Some((36, 415))); } + +/// The bytes of a `document.exportForWeb.saveColorTable` reply without a path. +fn color_table_file(s: &mut Session, p: Value) -> (Value, Vec) { + let v = run(s, "document.exportForWeb.saveColorTable", p); + let bytes = vectorcraft_format::base64_decode(v["dataBase64"].as_str().unwrap()).unwrap(); + (v, bytes) +} + +/// The color table file of `colors` (`#rrggbb`) and transparent entry `transparent`, as the +/// published layout gives it: 256 RGB triples (zero past the colors used), then the number of +/// colors and the transparent index (0xFFFF for none), two bytes each, most significant first. +fn act_layout(colors: &[&str], transparent: Option) -> Vec { + let mut out = vec![]; + for c in colors { + let rgb = u32::from_str_radix(c.trim_start_matches('#'), 16).unwrap(); + out.extend_from_slice(&[(rgb >> 16) as u8, (rgb >> 8) as u8, rgb as u8]); + } + out.resize(768, 0); + out.extend_from_slice(&(colors.len() as u16).to_be_bytes()); + out.extend_from_slice(&transparent.unwrap_or(0xFFFF).to_be_bytes()); + out +} + +/// Save Color Table writes the table the preview shows as a 772-byte color table file: the colors +/// as written, in file order, zero bytes after them, the count and the transparent entry. +#[test] +fn save_color_table_writes_the_act_layout() { + let mut s = two_colours(); + for format in ["gif", "png8"] { + let p = json!({"format": format, "dither": "none", "transparency": false}); + let pv = run(&mut s, "document.exportForWeb.preview", p.clone()); + let colors: Vec<&str> = pv["colors"].as_array().unwrap().iter().map(|c| c["color"].as_str().unwrap()).collect(); + assert_eq!(colors.len(), 2, "{pv}"); + let (v, bytes) = color_table_file(&mut s, p); + assert_eq!(bytes, act_layout(&colors, None), "{format}"); + assert_eq!((v["colors"].as_u64(), v["transparentIndex"].is_null(), v["bytes"].as_u64()), (Some(2), true, Some(772)), "{v}"); + } + // Transparent pixels: the trailer names the transparent entry. + let mut s = session(40.0, 30.0); + rect(&mut s, [10.0, 5.0, 10.0, 20.0], "#ff0000"); + let p = json!({"format": "gif", "antiAlias": "none", "dither": "none"}); + let pv = run(&mut s, "document.exportForWeb.preview", p.clone()); + let table = pv["colors"].as_array().unwrap(); + let at = table.iter().position(|c| c["transparent"] == true).expect("a transparent entry") as u16; + let colors: Vec<&str> = table.iter().map(|c| c["color"].as_str().unwrap()).collect(); + let (v, bytes) = color_table_file(&mut s, p); + assert_eq!(bytes, act_layout(&colors, Some(at))); + assert_eq!(v["transparentIndex"].as_u64(), Some(u64::from(at))); +} + +/// A color shifted by hand goes into the file as the color it is written as. +#[test] +fn save_color_table_writes_shifted_colors_as_written() { + let mut s = two_colours(); + let p = json!({"format": "gif", "dither": "none", "transparency": false, "colorTable": {"shifted": {"#ff0000": "#123456"}}}); + let (_, bytes) = color_table_file(&mut s, p); + let colors: Vec<[u8; 3]> = bytes[..6].chunks(3).map(|c| [c[0], c[1], c[2]]).collect(); + assert!(colors.contains(&[0x12, 0x34, 0x56]) && !colors.contains(&[255, 0, 0]), "{colors:?}"); +} + +/// Save Color Table writes the file at `path`, adding `.act` to a name without an extension and +/// keeping another extension, and refuses formats without a color table and bad params. +#[test] +fn save_color_table_writes_the_path_and_refuses_bad_params() { + let dir = std::env::temp_dir().join(format!("vc-color-table-save-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let mut s = two_colours(); + let p = json!({"format": "gif", "dither": "none"}); + let (_, bytes) = color_table_file(&mut s, p.clone()); + let bare = dir.join("table").to_string_lossy().into_owned(); + let v = run(&mut s, "document.exportForWeb.saveColorTable", merge(&p, json!({"path": bare}))); + let written = format!("{bare}.act"); + assert_eq!(v["path"].as_str(), Some(written.as_str())); + assert_eq!(std::fs::read(&written).unwrap(), bytes); + let other = dir.join("table.tbl").to_string_lossy().into_owned(); + run(&mut s, "document.exportForWeb.saveColorTable", merge(&p, json!({"path": other}))); + assert_eq!(std::fs::read(&other).unwrap(), bytes); + for (bad, says) in [ + (json!({"format": "jpg"}), "`jpg` has no color table"), + (json!({"format": "png24"}), "`png24` has no color table"), + (json!({"path": 5}), "`path` must be a string"), + (json!({"slice": "1"}), "`slice` is a slice number"), + (json!({"slice": 0}), "`slice` is a slice number"), + ] { + let e = s.execute("document.exportForWeb.saveColorTable", &bad).unwrap_err().to_string(); + assert!(e.contains(says), "{bad}: {e}"); + } + let _ = std::fs::remove_dir_all(dir); +} + +/// The preview refuses a `slice` that is not a slice number instead of previewing the whole image. +#[test] +fn preview_refuses_a_slice_that_is_not_a_number() { + let mut s = two_colours(); + for slice in [json!("1"), json!(0), json!(-1), json!(1.5)] { + let e = s.execute("document.exportForWeb.preview", &json!({"slice": slice})).unwrap_err().to_string(); + assert!(e.contains("`slice` is a slice number"), "{slice}: {e}"); + } + assert!(s.execute("document.exportForWeb.preview", &json!({"slice": null})).is_ok()); +} + +/// Color table files are read as the published layout gives them: 768 bytes are 256 colors without +/// a transparent entry; 772 bytes add the count and the transparent index. +#[test] +fn color_table_files_are_read_by_the_published_layout() { + use cmd::webexport::read_act; + let long: Vec = (0..768).map(|i| (i % 251) as u8).collect(); + let t = read_act(&long).unwrap(); + assert_eq!((t.colors.len(), t.colors[0], t.colors[255], t.transparent), (256, [0, 1, 2], [12, 13, 14], None)); + let t = read_act(&act_layout(&["#ff0000", "#00ff00", "#0000ff"], Some(1))).unwrap(); + assert_eq!((t.colors, t.transparent), (vec![[255, 0, 0], [0, 255, 0], [0, 0, 255]], Some(1))); + assert_eq!(read_act(&act_layout(&["#ff0000", "#00ff00"], None)).unwrap().transparent, None); + // An index past the colors used names no entry. + assert_eq!(read_act(&act_layout(&["#ff0000", "#00ff00"], Some(2))).unwrap().transparent, None); + let mut zero = act_layout(&["#ff0000"], None); + zero[768..770].copy_from_slice(&0u16.to_be_bytes()); + let mut over = act_layout(&["#ff0000"], None); + over[768..770].copy_from_slice(&257u16.to_be_bytes()); + for bad in [vec![], vec![0; 767], vec![0; 769], vec![0; 771], vec![0; 773], zero, over] { + assert!(read_act(&bad).unwrap_err().contains("not a color table"), "{} bytes", bad.len()); + } +} + +/// Load Color Table makes the file's colors the fixed palette, other than its transparent entry, +/// with the file's color count; the preview of the loaded settings writes those colors. +#[test] +fn load_color_table_makes_the_file_the_fixed_palette() { + let mut s = two_colours(); + let file = act_layout(&["#00ff00", "#ffffff", "#ff0000"], Some(1)); + let table = json!({ + "deleted": ["#0000ff"], "shifted": {"#ff0000": "#111111"}, "webShift": ["#ff0000"], "locked": ["#ff0000"], + "transparent": ["#00ff00"], "sort": "hue", + }); + let p = json!({"format": "gif", "dither": "none", "transparency": false, "webSnap": 100, "colorTable": table}); + let v = run(&mut s, "webExport.loadColorTable", merge(&p, json!({"dataBase64": vectorcraft_format::base64_encode(&file)}))); + assert_eq!((&v["colors"], &v["transparentIndex"]), (&json!(["#00ff00", "#ffffff", "#ff0000"]), &json!(1))); + let settings = &v["settings"]; + assert_eq!((&settings["colors"], &settings["webSnap"]), (&json!(3), &json!(0))); + let table = &settings["colorTable"]; + assert_eq!( + (&table["customPalette"], &table["deleted"], &table["shifted"], &table["webShift"]), + (&json!(["#00ff00", "#ff0000"]), &json!([]), &json!({}), &json!([])) + ); + assert_eq!((&table["locked"], &table["transparent"], &table["sort"]), (&json!([]), &json!([]), &json!("none"))); + // The loaded palette is what the image is written with: blue takes the nearest loaded color. + let pv = run(&mut s, "document.exportForWeb.preview", settings.clone()); + let written: Vec<&str> = pv["colors"].as_array().unwrap().iter().map(|c| c["color"].as_str().unwrap()).collect(); + assert!(!written.is_empty() && written.iter().all(|c| ["#00ff00", "#ff0000"].contains(c)), "{pv}"); + // A table saved and loaded again keeps its colors. + let opaque = json!({"format": "png8", "dither": "none", "transparency": false}); + let saved = color_table_file(&mut s, opaque.clone()).1; + let again = run(&mut s, "webExport.loadColorTable", json!({"format": "png8", "dataBase64": vectorcraft_format::base64_encode(&saved)})); + let shown = run(&mut s, "document.exportForWeb.preview", opaque); + let before: Vec<&Value> = shown["colors"].as_array().unwrap().iter().map(|c| &c["color"]).collect(); + assert_eq!(again["colors"].as_array().unwrap().iter().collect::>(), before); + // A table whose only color is its transparent entry loads that color. + let only = act_layout(&["#336699"], Some(0)); + let v = run(&mut s, "webExport.loadColorTable", json!({"dataBase64": vectorcraft_format::base64_encode(&only)})); + assert_eq!((&v["settings"]["colorTable"]["customPalette"], &v["settings"]["colors"]), (&json!(["#336699"]), &json!(2))); +} + +/// Load Color Table reads a path, reads no more of a file than a color table takes, and refuses +/// bad params without changing the remembered settings. +#[test] +fn load_color_table_reads_a_path_and_refuses_bad_params() { + let dir = std::env::temp_dir().join(format!("vc-color-table-load-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let mut s = two_colours(); + let path = dir.join("t.act").to_string_lossy().into_owned(); + std::fs::write(&path, act_layout(&["#010203", "#040506"], None)).unwrap(); + let v = run(&mut s, "webExport.loadColorTable", json!({"path": path})); + assert_eq!(v["settings"]["colorTable"]["customPalette"], json!(["#010203", "#040506"])); + let large = dir.join("large.act").to_string_lossy().into_owned(); + std::fs::write(&large, vec![0u8; 1 << 20]).unwrap(); + let b64 = vectorcraft_format::base64_encode(&act_layout(&["#010203"], None)); + for (bad, says) in [ + (json!({"path": large}), "not a color table"), + (json!({"dataBase64": vectorcraft_format::base64_encode(&[0u8; 100])}), "not a color table"), + // A whole table with more data after it is too long. + (json!({"dataBase64": format!("{b64}AAAA")}), "not a color table"), + (json!({}), "give exactly one of `path` and `dataBase64`"), + (json!({"path": path, "dataBase64": b64}), "give exactly one of `path` and `dataBase64`"), + (json!({"dataBase64": "%%%"}), "bad dataBase64"), + (json!({"dataBase64": b64, "format": "jpg"}), "`jpg` has no color table"), + ] { + let e = s.execute("webExport.loadColorTable", &bad).unwrap_err().to_string(); + assert!(e.contains(says), "{bad}: {e}"); + } + assert!(s.last_web_settings().color_table.custom_palette.is_empty(), "nothing is remembered"); + let _ = std::fs::remove_dir_all(dir); +} diff --git a/crates/ui-egui/src/dialogs/save_for_web.rs b/crates/ui-egui/src/dialogs/save_for_web.rs index 7376973d6f..0e05bf9ede 100644 --- a/crates/ui-egui/src/dialogs/save_for_web.rs +++ b/crates/ui-egui/src/dialogs/save_for_web.rs @@ -4,8 +4,8 @@ //! PNG-24), colour reduction, colours, dither, transparency and matte, interlacing, web snap, //! lossy, JPEG quality, the colour table (lock, map to transparent, web shift, sort, Delete Color, //! Restore Generated Table, a double-click that shifts a color to one picked in the Color Picker, -//! and Unshift All Colors), image size and anti-aliasing, Clip to Artboard, sRGB, metadata, -//! slices and HTML output, and presets. +//! Unshift All Colors, and Load Color Table… and Save Color Table… for `.act` files), image size +//! and anti-aliasing, Clip to Artboard, sRGB, metadata, slices and HTML output, and presets. //! //! Fields are the `document.exportForWeb` settings (`webExport.settings` gives them; set one with //! `ui.dialog.set`, or `preset` to load a preset), plus the dialog's own: `__view` (`original`, @@ -17,8 +17,9 @@ //! preset) and `__hasSlices`. Optimize to File Size… (`__optimizeOpen: true`) shows `__optimizeK` (the desired size in K), //! `__optimizeStart` (`current`, `auto`) and with slices `__optimizeUse` (`allSlices`, //! `eachSlice`, `currentSlice`); `__optimizeGo: true` runs `webExport.optimizeToFileSize` and -//! takes the settings it finds, and `__optimized` holds its result. Save… remembers -//! the settings and writes the files (`file.saveForWeb`); Done only remembers them; Preview in +//! takes the settings it finds, and `__optimized` holds its result. `__loadColorTable: true` and +//! `__saveColorTable: true` run the color table menu's Load Color Table… and Save Color Table…. +//! Save… remembers the settings and writes the files (`file.saveForWeb`); Done only remembers them; Preview in //! Browser opens the HTML page (`file.saveForWeb.browser`). While Alt (Option on macOS) is held, //! Cancel reads Reset, which puts the remembered settings back and leaves the dialog open //! (`ui.dialogReset`). The previews are what Save writes: @@ -568,6 +569,15 @@ fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { { app.status(e); } + // The color table menu's Load and Save, whose file dialogs answer later on some systems. + for (key, f) in [("__loadColorTable", load_color_table as ColorTableAction), ("__saveColorTable", save_color_table)] { + if d.fields.remove(key).is_some_and(|v| v == json!(true)) + && let Err(e) = crate::picks::in_dialog(app, d, f) + && e != "cancelled" + { + app.status(e); + } + } take_shift(d); let settings = settings_of(app, d); let mut browser = false; @@ -844,7 +854,7 @@ fn side(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog, s: Option<& choice(ui, d, "metadata", tl!("Metadata:"), &pairs(&WebMetadata::ALL, WebMetadata::key, WebMetadata::label)); if format.palette() { widgets::divider(ui); - if let Err(e) = color_table(ui, d, s) { + if let Err(e) = color_table(ui, d, s, io::is_web(app)) { app.status(e); } } @@ -1130,9 +1140,10 @@ fn matte_row(ui: &mut egui::Ui, d: &mut Dialog) { /// selects one color, a Shift-click the colors from the anchor, and a Ctrl-click /// (Command-click on macOS) adds or removes one; a double-click on an opaque color asks for the /// Color Picker (`__editColor`), and a color shifted by hand shows its source color at the upper -/// left and its new color at the lower right. Returns an error for a deletion that would leave -/// no color. -fn color_table(ui: &mut egui::Ui, d: &mut Dialog, s: Option<&WebSettings>) -> Result<(), String> { +/// left and its new color at the lower right. The menu's Load Color Table… and Save Color Table… +/// set `__loadColorTable` and `__saveColorTable` (Load is off on the `web`). Returns an error for a +/// deletion that would leave no color. +fn color_table(ui: &mut egui::Ui, d: &mut Dialog, s: Option<&WebSettings>, web: bool) -> Result<(), String> { let t = Tokens::get(ui.ctx()); let cache: Option = ui.ctx().data(|m| m.get_temp(cache_id())); let key = s.map(|s| s.to_json().to_string()); @@ -1293,6 +1304,14 @@ fn color_table(ui: &mut egui::Ui, d: &mut Dialog, s: Option<&WebSettings>) -> Re unshift_all = true; ui.close(); } + if widgets::menu_item(ui, tl!("Load Color Table…"), !web, false) { + d.fields.insert("__loadColorTable".into(), json!(true)); + ui.close(); + } + if widgets::menu_item(ui, tl!("Save Color Table…"), !shot.colors.is_empty(), false) { + d.fields.insert("__saveColorTable".into(), json!(true)); + ui.close(); + } }); }); let sort = table.sort; @@ -1495,6 +1514,37 @@ pub(super) fn unshift_all_colors(d: &mut Dialog) { set_table(d, "webShift", json!([])); } +/// A color table menu action that asks for a file. +type ColorTableAction = fn(&mut VectorcraftApp, &mut Dialog) -> Result<(), String>; + +/// The dialog's settings without the image's `path`. +pub(super) fn table_params(d: &Dialog) -> Value { + let mut p = params(d); + if let Some(o) = p.as_object_mut() { + o.remove("path"); + } + p +} + +/// Save Color Table…: the color table the preview shows, written to a picked `.act` file +/// (`document.exportForWeb.saveColorTable`; the web downloads it). The dialog does not change. +pub(super) fn save_color_table(app: &mut VectorcraftApp, d: &mut Dialog) -> Result<(), String> { + io::save_command_output(app, "document.exportForWeb.saveColorTable", webexport::COLOR_TABLE_EXT, table_params(d)).map(|_| ()) +} + +/// Load Color Table…: a picked `.act` file becomes the table's fixed palette, with its color count +/// (`webExport.loadColorTable`). +pub(super) fn load_color_table(app: &mut VectorcraftApp, d: &mut Dialog) -> Result<(), String> { + let pick = crate::FilePick { filters: vec![crate::FilePick::filter("Color tables", &[webexport::COLOR_TABLE_EXT])], ..Default::default() }; + let path = crate::picks::open(app, &pick).ok_or("cancelled")?; + let mut p = table_params(d); + p["path"] = json!(path); + let r = app.run("webExport.loadColorTable", p)?; + let settings: WebSettings = serde_json::from_value(r["settings"].clone()).map_err(|e| e.to_string())?; + d.fields.extend(settings_fields(&settings)); + Ok(()) +} + /// Add `color` to the colour table's `list`, or take it out. pub(super) fn toggle(d: &mut Dialog, list: &str, color: &str, add: bool) { let mut v: Vec = d.fields.get("colorTable").and_then(|t| t.get(list)).and_then(Value::as_array).cloned().unwrap_or_default(); diff --git a/crates/ui-egui/src/dialogs/tests_save_for_web.rs b/crates/ui-egui/src/dialogs/tests_save_for_web.rs index 63ed3e2ded..3ebdbee12a 100644 --- a/crates/ui-egui/src/dialogs/tests_save_for_web.rs +++ b/crates/ui-egui/src/dialogs/tests_save_for_web.rs @@ -844,6 +844,53 @@ fn colour_table_shift_unshift_and_unshift_all() { assert_eq!((&d.fields["colorTable"]["shifted"], &d.fields["colorTable"]["deleted"]), (&json!({}), &json!(["#222222"]))); } +/// Save Color Table… writes the table the preview shows to a picked `.act` file without changing +/// the dialog or the image's `path`; Load Color Table… makes a picked file the fixed palette. +#[test] +fn color_table_menu_saves_and_loads_act_files() { + let dir = vectorcraft_testkit::temp_dir("sfw-color-table"); + let (mut app, _) = app(&dir, false); + let picked = dir.join("loaded.act").to_string_lossy().into_owned(); + let open = picked.clone(); + app.services.pick_open = Some(Box::new(move |p: &crate::FilePick| { + assert_eq!(p.filters, [("Color tables".to_string(), vec!["act".to_string()])]); + Some(open.clone()) + })); + app.services.write = Some(Box::new(|p: &str, b: &[u8]| std::fs::write(p, b).map_err(|e| e.to_string()))); + app.run("file.saveForWeb", json!({})).unwrap(); + for (k, v) in [("format", json!("gif")), ("dither", json!("none")), ("transparency", json!(false)), ("path", json!("/elsewhere/page.gif"))] { + set(&mut app, k, v); + } + frame(&mut app); + let settings = save_for_web::table_params(app.ui.dialog.as_ref().unwrap()); + let want = app.run("document.exportForWeb.saveColorTable", settings).unwrap(); + let want = vectorcraft_format::base64_decode(want["dataBase64"].as_str().unwrap()).unwrap(); + let before = app.ui.dialog.as_ref().unwrap().fields.clone(); + set(&mut app, "__saveColorTable", json!(true)); + frame(&mut app); + let written = std::fs::read(dir.join("Untitled-1.act")).unwrap_or_else(|e| panic!("{e}: {}", app.ui.status)); + assert_eq!((written.len(), &written), (772, &want)); + assert_eq!(app.ui.dialog.as_ref().unwrap().fields, before, "the dialog does not change"); + assert!(app.ui.status.contains("Untitled-1.act"), "{}", app.ui.status); + // Load: three colors, the second one transparent. + let mut file = vec![0x11, 0x22, 0x33, 0, 0, 0, 0x44, 0x55, 0x66]; + file.resize(768, 0); + file.extend_from_slice(&[0, 3, 0, 1]); + std::fs::write(&picked, &file).unwrap(); + set(&mut app, "__loadColorTable", json!(true)); + frame(&mut app); + let fields = &app.ui.dialog.as_ref().unwrap().fields; + assert_eq!((&fields["colors"], &fields["colorTable"]["customPalette"]), (&json!(3), &json!(["#112233", "#445566"]))); + assert_eq!(fields["path"], "/elsewhere/page.gif"); + // A file that is not a color table changes nothing and says why. + std::fs::write(&picked, [0u8; 10]).unwrap(); + let before = app.ui.dialog.as_ref().unwrap().fields.clone(); + set(&mut app, "__loadColorTable", json!(true)); + frame(&mut app); + assert_eq!(app.ui.dialog.as_ref().unwrap().fields, before); + assert!(app.ui.status.contains("not a color table"), "{}", app.ui.status); +} + /// One frame of `app` in `ctx`, 50 ms after the last. fn tick(app: &mut VectorcraftApp, ctx: &egui::Context, events: Vec) { let time = ctx.input(|i| i.time) + 0.05; diff --git a/crates/ui-egui/src/i18n/bg.tsv b/crates/ui-egui/src/i18n/bg.tsv index 167737554d..16e30f44b2 100644 --- a/crates/ui-egui/src/i18n/bg.tsv +++ b/crates/ui-egui/src/i18n/bg.tsv @@ -826,6 +826,10 @@ font-technology Variable Променливи Delete Color Изтриване на цвят Restore Generated Table Възстановяване на генерираната таблица Unshift All Colors Преместване назад на всички цветове + Load Color Table… Зареди цветова таблица… + Load Color Table Зареди цветова таблица + Save Color Table… Запази цветова таблица… + Save Color Table Запази цветова таблица Delete Character Style Изтриване на стил за знаци Delete Empty Artboards Изтриване на празни работни области Delete Freeform Point Изтриване на свободна точка diff --git a/crates/ui-egui/src/i18n/bs.tsv b/crates/ui-egui/src/i18n/bs.tsv index a9d6e35ed8..4ef9e5ecf3 100644 --- a/crates/ui-egui/src/i18n/bs.tsv +++ b/crates/ui-egui/src/i18n/bs.tsv @@ -3638,6 +3638,10 @@ theme Appearance Izgled Delete Color Izbriši boju Restore Generated Table Vrati generisanu tabelu Unshift All Colors Poništi pomak svih boja + Load Color Table… Učitaj tabelu boja… + Load Color Table Učitaj tabelu boja + Save Color Table… Sačuvaj tabelu boja… + Save Color Table Sačuvaj tabelu boja Delete Symbol Izbriši simbol Delete the selected symbol? Izbrisati odabrani simbol? Delete the selected symbols? Izbrisati odabrane simbole? diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index e4271f7926..021ab71e35 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -1216,6 +1216,14 @@ arrowhead Target Diana Delete Color Suprimeix el color Restore Generated Table Restaura la taula generada Unshift All Colors Desfés el desplaçament de tots els colors + Load Color Table… Carrega la taula de colors… + Load Color Table Carrega la taula de colors + Save Color Table… Desa la taula de colors… + Save Color Table Desa la taula de colors +@msg `{format}` has no color table: use gif or png8 `{format}` no té taula de colors: utilitza gif o png8 +@msg not a color table: an .act file is 768 or 772 bytes long and uses 1 to 256 colors no és una taula de colors: un fitxer .act té 768 o 772 bytes i fa servir entre 1 i 256 colors +@msg give exactly one of `path` and `dataBase64` indica exactament un de `path` i `dataBase64` +@msg `slice` is a slice number from `slice.list` `slice` és un número de tall de `slice.list` Delete Character Style Suprimeix l’estil de caràcter Delete Data Set Suprimeix el conjunt de dades Delete Data Sets Suprimeix els conjunts de dades diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index 488df173c3..f52d449cce 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -3739,6 +3739,14 @@ theme Appearance Motiv Delete Color Odstranit barvu Restore Generated Table Obnovit vygenerovanou tabulku Unshift All Colors Zrušit posun všech barev + Load Color Table… Načíst tabulku barev… + Load Color Table Načíst tabulku barev + Save Color Table… Uložit tabulku barev… + Save Color Table Uložit tabulku barev +@msg `{format}` has no color table: use gif or png8 `{format}` nemá tabulku barev: použijte gif nebo png8 +@msg not a color table: an .act file is 768 or 772 bytes long and uses 1 to 256 colors není tabulka barev: soubor .act má 768 nebo 772 bajtů a používá 1 až 256 barev +@msg give exactly one of `path` and `dataBase64` zadejte právě jedno z `path` a `dataBase64` +@msg `slice` is a slice number from `slice.list` `slice` je číslo řezu ze `slice.list` Delete Symbol Odstranit symbol Delete the selected symbol? Odstranit vybraný symbol? Delete the selected symbols? Odstranit vybrané symboly? diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index 302ab6aa69..33f17fc79b 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -6219,6 +6219,14 @@ theme Appearance Udseende Delete Color Slet farve Restore Generated Table Gendan genereret tabel Unshift All Colors Fjern skift af alle farver + Load Color Table… Indlæs farvetabel… + Load Color Table Indlæs farvetabel + Save Color Table… Gem farvetabel… + Save Color Table Gem farvetabel +@msg `{format}` has no color table: use gif or png8 `{format}` har ingen farvetabel: brug gif eller png8 +@msg not a color table: an .act file is 768 or 772 bytes long and uses 1 to 256 colors ikke en farvetabel: en .act-fil er 768 eller 772 byte lang og bruger 1 til 256 farver +@msg give exactly one of `path` and `dataBase64` angiv præcis én af `path` og `dataBase64` +@msg `slice` is a slice number from `slice.list` `slice` er et udsnitsnummer fra `slice.list` Delete Symbol Slet symbol Delete the selected symbol? Vil du slette det markerede symbol? Delete the selected symbols? Vil du slette de markerede symboler? diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index 9482345f18..c40dbbdf51 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -839,6 +839,14 @@ font-technology Variable Variabel Delete Color Farbe löschen Restore Generated Table Generierte Tabelle wiederherstellen Unshift All Colors Verschiebung aller Farben aufheben + Load Color Table… Farbtabelle laden… + Load Color Table Farbtabelle laden + Save Color Table… Farbtabelle speichern… + Save Color Table Farbtabelle speichern +@msg `{format}` has no color table: use gif or png8 `{format}` hat keine Farbtabelle: verwenden Sie gif oder png8 +@msg not a color table: an .act file is 768 or 772 bytes long and uses 1 to 256 colors keine Farbtabelle: eine .act-Datei ist 768 oder 772 Byte lang und verwendet 1 bis 256 Farben +@msg give exactly one of `path` and `dataBase64` geben Sie genau eines von `path` und `dataBase64` an +@msg `slice` is a slice number from `slice.list` `slice` ist eine Slice-Nummer aus `slice.list` Delete Character Style Zeichenformat löschen Delete Empty Artboards Leere Zeichenflächen löschen Delete Freeform Point Freiformpunkt löschen diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index 434d0cc0b8..6b22367248 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -811,6 +811,14 @@ font-technology Variable Μεταβλητές Delete Color Διαγραφή χρώματος Restore Generated Table Επαναφορά του παραγόμενου πίνακα Unshift All Colors Αναίρεση μετατόπισης όλων των χρωμάτων + Load Color Table… Φόρτωση πίνακα χρωμάτων… + Load Color Table Φόρτωση πίνακα χρωμάτων + Save Color Table… Αποθήκευση πίνακα χρωμάτων… + Save Color Table Αποθήκευση πίνακα χρωμάτων +@msg `{format}` has no color table: use gif or png8 το `{format}` δεν έχει πίνακα χρωμάτων: χρησιμοποιήστε gif ή png8 +@msg not a color table: an .act file is 768 or 772 bytes long and uses 1 to 256 colors δεν είναι πίνακας χρωμάτων: ένα αρχείο .act έχει μήκος 768 ή 772 byte και χρησιμοποιεί 1 έως 256 χρώματα +@msg give exactly one of `path` and `dataBase64` δώστε ακριβώς ένα από τα `path` και `dataBase64` +@msg `slice` is a slice number from `slice.list` το `slice` είναι αριθμός τομής από το `slice.list` Delete Character Style Διαγραφή στυλ χαρακτήρων Delete Empty Artboards Διαγραφή κενών πινάκων σχεδίασης Delete Freeform Point Διαγραφή ελεύθερου σημείου diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index 3f83e928e4..fb17942a85 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -857,6 +857,14 @@ font-technology Variable Variables Delete Color Eliminar color Restore Generated Table Restaurar tabla generada Unshift All Colors Deshacer cambio de todos los colores + Load Color Table… Cargar tabla de colores… + Load Color Table Cargar tabla de colores + Save Color Table… Guardar tabla de colores… + Save Color Table Guardar tabla de colores +@msg `{format}` has no color table: use gif or png8 `{format}` no tiene tabla de colores: usa gif o png8 +@msg not a color table: an .act file is 768 or 772 bytes long and uses 1 to 256 colors no es una tabla de colores: un archivo .act tiene 768 o 772 bytes y usa de 1 a 256 colores +@msg give exactly one of `path` and `dataBase64` indica exactamente uno de `path` y `dataBase64` +@msg `slice` is a slice number from `slice.list` `slice` es un número de sector de `slice.list` Delete Character Style Eliminar estilo de carácter Delete Empty Artboards Eliminar mesas de trabajo vacías Delete Freeform Point Eliminar punto libre diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index a4d85b23e8..266205c3c2 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -3676,6 +3676,14 @@ theme Appearance Ulkoasu Delete Color Poista väri Restore Generated Table Palauta luotu taulukko Unshift All Colors Peru kaikkien värien siirto + Load Color Table… Lataa väritaulukko… + Load Color Table Lataa väritaulukko + Save Color Table… Tallenna väritaulukko… + Save Color Table Tallenna väritaulukko +@msg `{format}` has no color table: use gif or png8 muodossa `{format}` ei ole väritaulukkoa: käytä muotoa gif tai png8 +@msg not a color table: an .act file is 768 or 772 bytes long and uses 1 to 256 colors ei väritaulukko: .act-tiedosto on 768 tai 772 tavua pitkä ja käyttää vähintään 1 ja enintään 256 väriä +@msg give exactly one of `path` and `dataBase64` anna täsmälleen yksi näistä: `path` tai `dataBase64` +@msg `slice` is a slice number from `slice.list` `slice` on siivun numero luettelosta `slice.list` Delete Symbol Poista symboli Delete the selected symbol? Poistetaanko valittu symboli? Delete the selected symbols? Poistetaanko valitut symbolit? diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 8f56486157..b924859a61 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -859,6 +859,14 @@ font-technology Variable Variables Delete Color Supprimer la couleur Restore Generated Table Restaurer la table générée Unshift All Colors Annuler le décalage de toutes les couleurs + Load Color Table… Charger la table des couleurs… + Load Color Table Charger la table des couleurs + Save Color Table… Enregistrer la table des couleurs… + Save Color Table Enregistrer la table des couleurs +@msg `{format}` has no color table: use gif or png8 `{format}` n’a pas de table des couleurs, utilisez gif ou png8 +@msg not a color table: an .act file is 768 or 772 bytes long and uses 1 to 256 colors ce n’est pas une table des couleurs (un fichier .act fait 768 ou 772 octets et utilise de 1 à 256 couleurs) +@msg give exactly one of `path` and `dataBase64` indiquez exactement un paramètre parmi `path` et `dataBase64` +@msg `slice` is a slice number from `slice.list` `slice` est un numéro de tranche de `slice.list` Delete Character Style Supprimer le style de caractère Delete Empty Artboards Supprimer les plans de travail vides Delete Freeform Point Supprimer le point libre diff --git a/crates/ui-egui/src/i18n/gu.tsv b/crates/ui-egui/src/i18n/gu.tsv index 0bb7c9b71f..fa4da5ca99 100644 --- a/crates/ui-egui/src/i18n/gu.tsv +++ b/crates/ui-egui/src/i18n/gu.tsv @@ -981,6 +981,10 @@ Delete Color રંગ કાઢી નાખો Restore Generated Table જનરેટ થયેલું ટેબલ પુનઃસ્થાપિત કરો Unshift All Colors બધા રંગોનું શિફ્ટ રદ કરો + Load Color Table… રંગ ટેબલ લોડ કરો… + Load Color Table રંગ ટેબલ લોડ કરો + Save Color Table… રંગ ટેબલ સાચવો… + Save Color Table રંગ ટેબલ સાચવો Delete Character Style અક્ષર સ્ટાઇલ કાઢી નાખો Delete Data Set ડેટા સેટ કાઢી નાખો Delete Data Sets ડેટા સેટ્સ કાઢી નાખો diff --git a/crates/ui-egui/src/i18n/hi.tsv b/crates/ui-egui/src/i18n/hi.tsv index e9509d9202..21ee78d672 100644 --- a/crates/ui-egui/src/i18n/hi.tsv +++ b/crates/ui-egui/src/i18n/hi.tsv @@ -1634,6 +1634,14 @@ arrowhead Feather पंख Delete Color रंग हटाएँ Restore Generated Table जनरेट की गई तालिका पुनर्स्थापित करें Unshift All Colors सभी रंग अनशिफ़्ट करें + Load Color Table… रंग तालिका लोड करें… + Load Color Table रंग तालिका लोड करें + Save Color Table… रंग तालिका सेव करें… + Save Color Table रंग तालिका सेव करें +@msg `{format}` has no color table: use gif or png8 `{format}` में रंग तालिका नहीं है: gif या png8 का उपयोग करें +@msg not a color table: an .act file is 768 or 772 bytes long and uses 1 to 256 colors यह रंग तालिका नहीं है: .act फ़ाइल 768 या 772 बाइट लंबी होती है और 1 से 256 रंगों का उपयोग करती है +@msg give exactly one of `path` and `dataBase64` `path` और `dataBase64` में से ठीक एक दें +@msg `slice` is a slice number from `slice.list` `slice`, `slice.list` से स्लाइस संख्या है Delete Character Style कैरेक्टर स्टाइल हटाएँ Delete Data Set डेटा सेट हटाएँ Delete Data Sets डेटा सेट्स हटाएँ diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index 87f050ef0d..46d10b4970 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -1106,6 +1106,14 @@ arrowhead Target Céltábla Delete Color Szín törlése Restore Generated Table Előállított tábla visszaállítása Unshift All Colors Az összes szín eltolásának visszavonása + Load Color Table… Színtábla betöltése… + Load Color Table Színtábla betöltése + Save Color Table… Színtábla mentése… + Save Color Table Színtábla mentése +@msg `{format}` has no color table: use gif or png8 a(z) `{format}` formátumnak nincs színtáblája: használj gif vagy png8 formátumot +@msg not a color table: an .act file is 768 or 772 bytes long and uses 1 to 256 colors nem színtábla: egy .act fájl 768 vagy 772 bájt hosszú, és 1 és 256 közötti számú színt használ +@msg give exactly one of `path` and `dataBase64` pontosan egyet adj meg ezek közül: `path`, `dataBase64` +@msg `slice` is a slice number from `slice.list` a `slice` egy szeletszám a `slice.list` listából Delete Character Style Karakterstílus törlése Delete Data Set Adatkészlet törlése Delete Empty Artboards Üres rajztáblák törlése diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index 924d3d80b5..1e0ed2b941 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -4087,6 +4087,14 @@ theme Appearance Tampilan Delete Color Hapus warna Restore Generated Table Pulihkan tabel yang dibuat Unshift All Colors Batalkan pergeseran semua warna + Load Color Table… Muat tabel warna… + Load Color Table Muat tabel warna + Save Color Table… Simpan tabel warna… + Save Color Table Simpan tabel warna +@msg `{format}` has no color table: use gif or png8 `{format}` tidak memiliki tabel warna: gunakan gif atau png8 +@msg not a color table: an .act file is 768 or 772 bytes long and uses 1 to 256 colors bukan tabel warna: file .act berukuran 768 atau 772 byte dan memakai 1 sampai 256 warna +@msg give exactly one of `path` and `dataBase64` berikan tepat satu dari `path` dan `dataBase64` +@msg `slice` is a slice number from `slice.list` `slice` adalah nomor slice dari `slice.list` Delete Symbol Hapus simbol Delete the selected symbol? Hapus simbol yang dipilih? Delete the selected symbols? Hapus simbol yang dipilih? diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index 5f47e3f117..791d0ffc2b 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -860,6 +860,14 @@ font-technology Variable Variabili Delete Color Elimina colore Restore Generated Table Ripristina tabella generata Unshift All Colors Annulla spostamento di tutti i colori + Load Color Table… Carica tabella colori… + Load Color Table Carica tabella colori + Save Color Table… Salva tabella colori… + Save Color Table Salva tabella colori +@msg `{format}` has no color table: use gif or png8 `{format}` non ha una tabella colori: usa gif o png8 +@msg not a color table: an .act file is 768 or 772 bytes long and uses 1 to 256 colors non è una tabella colori: un file .act è lungo 768 o 772 byte e usa da 1 a 256 colori +@msg give exactly one of `path` and `dataBase64` indica esattamente uno tra `path` e `dataBase64` +@msg `slice` is a slice number from `slice.list` `slice` è un numero di sezione da `slice.list` Delete Character Style Elimina stile carattere Delete Empty Artboards Elimina tavole da disegno vuote Delete Freeform Point Elimina punto libero diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index 9a1b5f6354..5dda57f454 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -1630,6 +1630,14 @@ antiAlias Sharp シャープ Delete Color カラーを削除 Restore Generated Table 生成されたテーブルを復元 Unshift All Colors すべてのカラーのシフトを戻す + Load Color Table… カラーテーブルを読み込み… + Load Color Table カラーテーブルを読み込み + Save Color Table… カラーテーブルを保存… + Save Color Table カラーテーブルを保存 +@msg `{format}` has no color table: use gif or png8 `{format}` にはカラーテーブルがありません: gif または png8 を使ってください +@msg not a color table: an .act file is 768 or 772 bytes long and uses 1 to 256 colors カラーテーブルではありません: .act ファイルは 768 または 772 バイトで、1 から 256 色を使います +@msg give exactly one of `path` and `dataBase64` `path` と `dataBase64` のうち 1 つだけを指定してください +@msg `slice` is a slice number from `slice.list` `slice` は `slice.list` のスライス番号です Delete Character Style 文字スタイルを削除 Delete Empty Artboards 空のアートボードを削除 Delete Freeform Point フリーフォームポイントを削除 diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index 8eeacee621..45233bc1e1 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -5497,6 +5497,14 @@ theme Appearance იერსახე Delete Color ფერის წაშლა Restore Generated Table გენერირებული ცხრილის აღდგენა Unshift All Colors ყველა ფერის წანაცვლების მოხსნა + Load Color Table… ფერების ცხრილის ჩატვირთვა… + Load Color Table ფერების ცხრილის ჩატვირთვა + Save Color Table… ფერების ცხრილის შენახვა… + Save Color Table ფერების ცხრილის შენახვა +@msg `{format}` has no color table: use gif or png8 `{format}`-ს არ აქვს ფერების ცხრილი: გამოიყენეთ gif ან png8 +@msg not a color table: an .act file is 768 or 772 bytes long and uses 1 to 256 colors ეს არ არის ფერების ცხრილი: .act ფაილი 768 ან 772 ბაიტია და იყენებს 1-დან 256 ფერამდე +@msg give exactly one of `path` and `dataBase64` მიუთითეთ ზუსტად ერთი: `path` ან `dataBase64` +@msg `slice` is a slice number from `slice.list` `slice` არის ნაჭრის ნომერი `slice.list`-დან Delete Symbol სიმბოლოს წაშლა Delete the selected symbol? წაიშალოს მონიშნული სიმბოლო? Delete the selected symbols? წაიშალოს მონიშნული სიმბოლოები? diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index 57e0b8be10..b293ac923a 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -1620,6 +1620,14 @@ antiAlias Sharp 날카롭게 Delete Color 색상 삭제 Restore Generated Table 생성된 표 복원 Unshift All Colors 모든 색상 이동 취소 + Load Color Table… 색상 표 불러오기… + Load Color Table 색상 표 불러오기 + Save Color Table… 색상 표 저장… + Save Color Table 색상 표 저장 +@msg `{format}` has no color table: use gif or png8 `{format}`에는 색상 표가 없습니다: gif 또는 png8을 사용하세요 +@msg not a color table: an .act file is 768 or 772 bytes long and uses 1 to 256 colors 색상 표가 아닙니다: .act 파일은 768 또는 772바이트이며 1개에서 256개까지의 색상을 사용합니다 +@msg give exactly one of `path` and `dataBase64` `path`, `dataBase64` 중 정확히 하나를 지정하세요 +@msg `slice` is a slice number from `slice.list` `slice`는 `slice.list`의 분할 번호입니다 Delete Character Style 문자 스타일 삭제 Delete Empty Artboards 빈 아트보드 삭제 Delete Freeform Point 자유 형태 포인트 삭제 diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index 5ed5cdc3e0..56b2baa10e 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -4085,6 +4085,14 @@ theme Appearance Vormgeving Delete Color Kleur verwijderen Restore Generated Table Gegenereerde tabel herstellen Unshift All Colors Verschuiving van alle kleuren ongedaan maken + Load Color Table… Kleurentabel laden… + Load Color Table Kleurentabel laden + Save Color Table… Kleurentabel opslaan… + Save Color Table Kleurentabel opslaan +@msg `{format}` has no color table: use gif or png8 `{format}` heeft geen kleurentabel: gebruik gif of png8 +@msg not a color table: an .act file is 768 or 772 bytes long and uses 1 to 256 colors geen kleurentabel: een .act-bestand is 768 of 772 bytes lang en gebruikt 1 tot 256 kleuren +@msg give exactly one of `path` and `dataBase64` geef precies een van `path` en `dataBase64` +@msg `slice` is a slice number from `slice.list` `slice` is een slicenummer uit `slice.list` Delete Symbol Symbool verwijderen Delete the selected symbol? Het geselecteerde symbool verwijderen? Delete the selected symbols? De geselecteerde symbolen verwijderen? diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index 74029133dc..867fc2245e 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -3618,6 +3618,14 @@ theme Appearance Wygląd Delete Color Usuń kolor Restore Generated Table Przywróć wygenerowaną tablicę Unshift All Colors Cofnij przesunięcie wszystkich kolorów + Load Color Table… Wczytaj tablicę kolorów… + Load Color Table Wczytaj tablicę kolorów + Save Color Table… Zapisz tablicę kolorów… + Save Color Table Zapisz tablicę kolorów +@msg `{format}` has no color table: use gif or png8 `{format}` nie ma tablicy kolorów: użyj gif lub png8 +@msg not a color table: an .act file is 768 or 772 bytes long and uses 1 to 256 colors to nie jest tablica kolorów: plik .act ma 768 lub 772 bajty i używa od 1 do 256 kolorów +@msg give exactly one of `path` and `dataBase64` podaj dokładnie jedno z: `path` i `dataBase64` +@msg `slice` is a slice number from `slice.list` `slice` to numer plasterka z `slice.list` Delete Symbol Usuń symbol Delete the selected symbol? Usunąć zaznaczony symbol? Delete the selected symbols? Usunąć zaznaczone symbole? diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index a1747af0b2..cea7326a84 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -786,6 +786,14 @@ antiAlias Sharp Nítido Delete Color Excluir Cor Restore Generated Table Restaurar Tabela Gerada Unshift All Colors Desfazer Mudança de Todas as Cores + Load Color Table… Carregar Tabela de Cores… + Load Color Table Carregar Tabela de Cores + Save Color Table… Salvar Tabela de Cores… + Save Color Table Salvar Tabela de Cores +@msg `{format}` has no color table: use gif or png8 `{format}` não tem tabela de cores: use gif ou png8 +@msg not a color table: an .act file is 768 or 772 bytes long and uses 1 to 256 colors não é uma tabela de cores: um arquivo .act tem 768 ou 772 bytes e usa de 1 a 256 cores +@msg give exactly one of `path` and `dataBase64` informe exatamente um de `path` e `dataBase64` +@msg `slice` is a slice number from `slice.list` `slice` é um número de fatia de `slice.list` Delete Character Style Excluir Estilo de Caractere Delete Empty Artboards Excluir Mesas de Trabalho Vazias Delete Freeform Point Excluir Ponto Livre diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index ca0c8d5145..7748cb5990 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -855,6 +855,14 @@ font-technology Variable Вариативные Delete Color Удалить цвет Restore Generated Table Восстановить созданную таблицу Unshift All Colors Отменить сдвиг всех цветов + Load Color Table… Загрузить цветовую таблицу… + Load Color Table Загрузить цветовую таблицу + Save Color Table… Сохранить цветовую таблицу… + Save Color Table Сохранить цветовую таблицу +@msg `{format}` has no color table: use gif or png8 у `{format}` нет цветовой таблицы: используйте gif или png8 +@msg not a color table: an .act file is 768 or 772 bytes long and uses 1 to 256 colors это не цветовая таблица: файл .act имеет длину 768 или 772 байта и использует от 1 до 256 цветов +@msg give exactly one of `path` and `dataBase64` укажите ровно одно из: `path` и `dataBase64` +@msg `slice` is a slice number from `slice.list` `slice` задаёт номер фрагмента из `slice.list` Delete Character Style Удалить стиль символа Delete Empty Artboards Удалить пустые монтажные области Delete Freeform Point Удалить произвольную точку diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index c26474cf93..6c78516f51 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -840,6 +840,14 @@ font-technology Variable Variabla Delete Color Radera färg Restore Generated Table Återställ genererad tabell Unshift All Colors Ta bort förskjutning av alla färger + Load Color Table… Läs in färgtabell… + Load Color Table Läs in färgtabell + Save Color Table… Spara färgtabell… + Save Color Table Spara färgtabell +@msg `{format}` has no color table: use gif or png8 `{format}` har ingen färgtabell: använd gif eller png8 +@msg not a color table: an .act file is 768 or 772 bytes long and uses 1 to 256 colors inte en färgtabell: en .act-fil är 768 eller 772 byte lång och använder 1 till 256 färger +@msg give exactly one of `path` and `dataBase64` ange exakt en av `path` och `dataBase64` +@msg `slice` is a slice number from `slice.list` `slice` är ett skivnummer från `slice.list` Delete Character Style Radera teckenstil Delete Empty Artboards Radera tomma ritytor Delete Freeform Point Radera fri punkt diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index 82186ebcdd..0ab10863c5 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -836,6 +836,14 @@ font-technology Variable Değişken Delete Color Rengi Sil Restore Generated Table Oluşturulan Tabloyu Geri Yükle Unshift All Colors Tüm Renklerin Kaydırmasını Kaldır + Load Color Table… Renk Tablosunu Yükle… + Load Color Table Renk Tablosunu Yükle + Save Color Table… Renk Tablosunu Kaydet… + Save Color Table Renk Tablosunu Kaydet +@msg `{format}` has no color table: use gif or png8 `{format}` biçiminin renk tablosu yok: gif veya png8 kullanın +@msg not a color table: an .act file is 768 or 772 bytes long and uses 1 to 256 colors renk tablosu değil: bir .act dosyası 768 veya 772 bayt uzunluğundadır ve 1 ile 256 arasında renk kullanır +@msg give exactly one of `path` and `dataBase64` `path` ve `dataBase64` değerlerinden tam olarak birini verin +@msg `slice` is a slice number from `slice.list` `slice`, `slice.list` içindeki bir dilim numarasıdır Delete Character Style Karakter Stilini Sil Delete Empty Artboards Boş Çalışma Yüzeylerini Sil Delete Freeform Point Serbest Biçim Noktasını Sil diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index de3329ef10..5c60f06b06 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -854,6 +854,14 @@ font-technology Variable Варіативні Delete Color Видалити колір Restore Generated Table Відновити створену таблицю Unshift All Colors Скасувати зсув усіх кольорів + Load Color Table… Завантажити колірну таблицю… + Load Color Table Завантажити колірну таблицю + Save Color Table… Зберегти колірну таблицю… + Save Color Table Зберегти колірну таблицю +@msg `{format}` has no color table: use gif or png8 `{format}` не має колірної таблиці: використайте gif або png8 +@msg not a color table: an .act file is 768 or 772 bytes long and uses 1 to 256 colors це не колірна таблиця: файл .act має довжину 768 або 772 байти й використовує від 1 до 256 кольорів +@msg give exactly one of `path` and `dataBase64` укажіть рівно одне з: `path`, `dataBase64` +@msg `slice` is a slice number from `slice.list` `slice` задає номер фрагмента зі `slice.list` Delete Character Style Видалити стиль символу Delete Empty Artboards Видалити порожні монтажні області Delete Freeform Point Видалити довільну точку diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index 675143a8d6..42ef6d153c 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -1002,6 +1002,14 @@ font-technology Variable Biến thiên Delete Color Xóa màu Restore Generated Table Khôi phục bảng đã tạo Unshift All Colors Bỏ dịch chuyển tất cả màu + Load Color Table… Tải bảng màu… + Load Color Table Tải bảng màu + Save Color Table… Lưu bảng màu… + Save Color Table Lưu bảng màu +@msg `{format}` has no color table: use gif or png8 `{format}` không có bảng màu: hãy dùng gif hoặc png8 +@msg not a color table: an .act file is 768 or 772 bytes long and uses 1 to 256 colors không phải bảng màu: tệp .act dài 768 hoặc 772 byte và dùng từ 1 đến 256 màu +@msg give exactly one of `path` and `dataBase64` hãy cho đúng một trong `path` và `dataBase64` +@msg `slice` is a slice number from `slice.list` `slice` là số lát cắt từ `slice.list` Delete Character Style Xóa kiểu ký tự Delete Data Set Xóa tập dữ liệu Delete Design Xóa thiết kế diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index 57f6a4403b..beac4b000d 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -801,6 +801,14 @@ antiAlias Sharp 锐利 Delete Color 删除颜色 Restore Generated Table 恢复生成的颜色表 Unshift All Colors 取消偏移所有颜色 + Load Color Table… 加载颜色表… + Load Color Table 加载颜色表 + Save Color Table… 保存颜色表… + Save Color Table 保存颜色表 +@msg `{format}` has no color table: use gif or png8 `{format}` 没有颜色表:请使用 gif 或 png8 +@msg not a color table: an .act file is 768 or 772 bytes long and uses 1 to 256 colors 不是颜色表:.act 文件长 768 或 772 字节,使用 1 到 256 种颜色 +@msg give exactly one of `path` and `dataBase64` `path` 和 `dataBase64` 中必须且只能给出一个 +@msg `slice` is a slice number from `slice.list` `slice` 是 `slice.list` 中的切片编号 Delete Character Style 删除字符样式 Delete Empty Artboards 删除空白画板 Delete Freeform Point 删除自由点 diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index 9834c17ea6..2b0232c1c6 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -822,6 +822,14 @@ font-technology Variable 可變 Delete Color 刪除顏色 Restore Generated Table 還原產生的色彩表 Unshift All Colors 取消位移所有顏色 + Load Color Table… 載入色彩表… + Load Color Table 載入色彩表 + Save Color Table… 儲存色彩表… + Save Color Table 儲存色彩表 +@msg `{format}` has no color table: use gif or png8 `{format}` 沒有色彩表:請使用 gif 或 png8 +@msg not a color table: an .act file is 768 or 772 bytes long and uses 1 to 256 colors 不是色彩表:.act 檔案長 768 或 772 位元組,使用 1 到 256 種顏色 +@msg give exactly one of `path` and `dataBase64` `path` 和 `dataBase64` 請只提供其中一個 +@msg `slice` is a slice number from `slice.list` `slice` 是 `slice.list` 中的切片編號 Delete Character Style 刪除字元樣式 Delete Empty Artboards 刪除空白工作區域 Delete Freeform Point 刪除任意形狀錨點 diff --git a/crates/ui-egui/src/io/save.rs b/crates/ui-egui/src/io/save.rs index aa4b565c07..927ff6231b 100644 --- a/crates/ui-egui/src/io/save.rs +++ b/crates/ui-egui/src/io/save.rs @@ -158,6 +158,7 @@ const FILE_TYPES: &[(&str, &[&str])] = &[ ("Action sets", &[crate::panels::actions::ACTIONS_EXT]), ("Export presets", fileio::SCREEN_EXPORT_PRESET_EXTS), ("Composite fonts", vectorcraft_engine::cmd::compositefonts::EXTS), + ("Color tables", &[vectorcraft_engine::cmd::webexport::COLOR_TABLE_EXT]), ("CSS", &["css"]), ("PostScript", &["ps"]), ("Preferences", &["json"]), diff --git a/docs/mcp.md b/docs/mcp.md index e7abf476a9..29b05a8090 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -10527,7 +10527,8 @@ couldn't be decoded and is missing from the image; the files are written all the file size), `seconds` to download at `kbps` (default 56.6), the size, and for palette formats the colour table (`colors: [{color, source, transparent, locked, webShifted, shifted, webSafe}]`). The colour table's lists name colours by `source` (the colour the reduction made), so a colour keeps its edits when it is web-shifted or snapped. `slice: n` -previews one slice; `image: true` adds the file; `warnings` holds the export's warnings. +previews one slice, and a `slice` that is not a whole number from 1 up is an error; `image: true` adds the file; +`warnings` holds the export's warnings. Delete Color is `colorTable.deleted: ["#rrggbb"…]`, by `source`. The deleted colors leave the table and the file, and their pixels take the nearest color left, with the current reduction's color distance and dither; the preview and the @@ -10567,6 +10568,29 @@ leaves the table as it was. A shifted swatch shows the source color at its upper right, with the lock mark, and Lock stays on until the color is unshifted. Web Shift replaces a shift by hand, and Unshift All Colors in the table's menu clears `shifted` and `webShift`. Only Web Colors in the picker starts off. +Save Color Table… in the table's menu is `document.exportForWeb.saveColorTable {path?, slice?, …settings}`. It writes +the GIF or PNG-8 color table the preview shows as a color table file (`.act`) in the layout the file format +specification gives (https://www.adobe.com/devnet-apps/photoshop/fileformatashtml/): 256 entries of three bytes (red, +green, blue) in file order, with zero bytes after the colors used, then the number of colors used and the index of the +transparent entry, two bytes each with the most significant byte first. The file is always 772 bytes, and the index is +65535 when the table has no transparent entry. A color shifted by hand is written as its new color. `.act` is added to +a `path` without an extension, and without `path` the file comes back as `dataBase64`. The reply is `{path, colors, +transparentIndex, bytes, warnings}` (`transparentIndex` is null when there is none). JPEG and PNG-24 are errors, and the +document and the settings do not change. Load Color Table… is `webExport.loadColorTable {path | dataBase64, +…settings}`. It reads a 768-byte file (256 colors, no transparent entry) or a 772-byte one (the number of colors used, +1 to 256, and the transparent entry's index; an index past the colors used names no entry) and returns +`{colors, transparentIndex, settings}`: the settings with the file's colors other than its transparent entry as +`colorTable.customPalette`, `colors` set to the number of colors the file uses (at least 2), the table's other edits +(`locked`, `transparent`, `deleted`, `shifted`, `webShift` and `sort`) cleared and `webSnap` set to 0, so every loaded +color is written as it is, in the file's order, and none is locked. A file whose only color is its +transparent entry loads that color. Another file size (base64 text included), a count of 0 or above 256, both or +neither of `path` and `dataBase64`, and JPEG or PNG-24 are errors; the command reads at most 773 bytes of a file and +remembers nothing. In +the dialog Load Color Table… puts the loaded settings into its fields (`__loadColorTable: true`), and Save Color Table… +writes the file picked in a save panel (`__saveColorTable: true`), or downloads it on the web, where Load Color Table… +is disabled. The help page describes both entries +(https://help.adobe.com/archive/en_US/illustrator/cs4/illustrator_cs4_help.pdf#page=404). + ```json {"name":"run_command","arguments":{"command":"document.exportForWeb.preview","params":{"format":"png8","colorTable":{"deleted":["#ff0000"],"customPalette":["#0000ff","#00ff00","#ff0000"]}}}} ``` diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 57ac87a396..f933a6fe0a 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1005,6 +1005,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - Save for Web: while Alt (Option on macOS) is held, the dialog's Cancel button reads Reset, which puts the remembered settings back on the document's active artboard and leaves the dialog open (`ui.dialogReset`). - Save for Web: the color table's trash button and Delete Color in its menu remove the selected GIF or PNG-8 colors, and their pixels take the nearest color left in the palette ([the help page](https://help.adobe.com/archive/en_US/illustrator/cs4/illustrator_cs4_help.pdf#page=404)). Click selects one color, Shift-click a range and Ctrl-click (Command-click on macOS) adds or removes one ([the help page](https://help.adobe.com/archive/en_US/illustrator/cs3/illustrator_cs3_help.pdf#page=398)). After the first deletion the table is a fixed Custom palette, so deleted colors stay out when the preview updates. These rules are VectorCraft's own: a deleted color is no longer locked, transparent or web-shifted; deleting every opaque color is refused; Restore Generated Table in the menu, or another reduction, goes back to the generated palette; presets and the remembered settings keep the edit (`colorTable.deleted`, `colorTable.customPalette`). Fixed palettes can also use all 256 entries when nothing is transparent. Scores and estimates are unchanged. - Save for Web: double-clicking a GIF or PNG-8 color-table swatch opens the Color Picker, and its OK changes that color to the one picked everywhere it appears in the image. The swatch then shows the original color in its upper-left half and the new one in its lower-right half, with the lock mark, and the color stays through a lower color count. Double-clicking a changed swatch opens the picker on the original color, and OK on it changes the color back; Unshift All Colors in the table's menu undoes every change, web shifts included ([the help page](https://help.adobe.com/archive/en_US/illustrator/cs3/illustrator_cs3_help.pdf#page=398)). These rules are VectorCraft's own: Cancel changes nothing; a changed color wins over Web Shift, Web Snap and Lock, and pressing Web Shift replaces it; a color mapped to transparent stays transparent; two colors may change to the same color; a changed color takes a kept palette slot before a locked one, and one slot always stays for the reduction; the change is kept by source color when the reduction changes and applies only while that source is in the table; presets and the remembered settings keep it; the picker opens with Only Web Colors off (`colorTable.shifted`). GIF lossy compression moves no pixel into or out of a changed color. Scores and estimates are unchanged. + - Save for Web: Save Color Table… in the color table's menu writes the GIF or PNG-8 table the preview shows to an `.act` file, and Load Color Table… reads one back as the table's fixed Custom palette, so the image is written with the loaded colors; reloaded colors come back as plain, unlocked entries ([the help page](https://help.adobe.com/archive/en_US/illustrator/cs4/illustrator_cs4_help.pdf#page=404)). The file follows the published color table layout (https://www.adobe.com/devnet-apps/photoshop/fileformatashtml/): 256 RGB entries in file order, then the number of colors and the transparent entry. These rules are VectorCraft's own: Save always writes the 772-byte form, with zero bytes after the colors used and 65535 when there is no transparent entry; Load takes the 768-byte and 772-byte forms, leaves the transparent entry out of the palette, sets Colors to the file's count, clears the table's other edits and its sort, and sets Web Snap to 0; Load reads only `.act` files and is disabled on the web (`document.exportForWeb.saveColorTable`, `webExport.loadColorTable`). Scores and estimates are unchanged. - Export for Screens, Save for Web (slice images, and files named after the document's title) and the Libraries panel name files with the characters Windows does not allow written as `-` and with a `-` after a Windows device name such as `CON`, on every platform (`document.exportForScreens`, `document.exportForWeb`, `library.create`). - Variables (data merge): text, visibility and image variables bound to objects (an object may carry several), dataset rows applied in one undo step (`variable.*`, `dataset.*`) from a Variables panel and Window › Variables, with dialogs to define, bind and edit, Make Text/Visibility/Image Dynamic, Capture/Update Data Set, CSV import/export (`dataset.import` / `dataset.export`), and a row in italics when an edit leaves the art not matching it; an image dataset value is a file path and apply keeps the object's bounds; bindings let go of deleted art and locked art is left alone except by visibility values; every command, like the rest, is drivable over MCP and the CLI. - Export for Screens numbers distinct row files whose names collide, compared without case, as `-2`, `-3`… instead of leaving them out; identical rows still write one file. It puts row folders that differ only in case into one folder (`document.exportForScreens`). From f6593b16dcdbc460cdb0139b322aeedcdc1295e9 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 20 Nov 2026 18:50:09 -0800 Subject: [PATCH 016/151] Properties: the Profile row stays while another selected stroke has a variable width --- crates/engine/src/cmd/stroke.rs | 38 ++++++++++++++---- crates/engine/src/tests/appearance.rs | 33 +++++++++++++++ crates/ui-egui/src/panels/properties.rs | 24 ++++++++++- crates/ui-egui/src/panels/properties/tests.rs | 40 +++++++++++++++++++ 4 files changed, 127 insertions(+), 8 deletions(-) diff --git a/crates/engine/src/cmd/stroke.rs b/crates/engine/src/cmd/stroke.rs index cb5d1fd374..4fc79b3277 100644 --- a/crates/engine/src/cmd/stroke.rs +++ b/crates/engine/src/cmd/stroke.rs @@ -497,6 +497,32 @@ impl Session { /// and with a target that has no stroke row, since `stroke.set` gives such a target a plain /// stroke. pub fn brushed_strokes_profiled(&self) -> Option { + let st = self.active()?; + let strokes: Vec<&StrokeLayer> = self.edited_strokes(false)?.into_iter().map(|s| s.filter(|s| s.brush.is_some())).collect::>()?; + if strokes.is_empty() { + return None; + } + // The library is read only when every stroke names a brush. + let lib = vectorcraft_brush::library(&st.doc); + strokes.iter().all(|s| vectorcraft_brush::keeps_brush_size(&lib, s)).then(|| strokes.iter().any(|s| s.profile.is_some())) + } + + /// Does any of the strokes that `stroke.set` edits without `ids` or `item` have a width + /// profile? The strokes are the ones [`Session::brushed_strokes_profiled`] reads, with or without + /// a brush. Type without an active Appearance row is left out, since `stroke.set` gives its + /// characters no profile. False with nothing selected, with an object inside a symbol instance + /// selected, and with a target that has no stroke row, which a profile from `stroke.set` would + /// give a plain stroke. + pub fn edited_strokes_profiled(&self) -> bool { + self.edited_strokes(true) + .and_then(|strokes| strokes.into_iter().collect::>>()) + .is_some_and(|strokes| strokes.iter().any(|s| s.profile.is_some())) + } + + /// The strokes that `stroke.set` edits without `ids` or `item`, one for each target, `None` for + /// a target without a stroke row (see [`Session::brushed_strokes_profiled`]). Type without an + /// active Appearance row is skipped with `skip_type`, and makes the result `None` without it. + fn edited_strokes(&self, skip_type: bool) -> Option>> { const C: &str = "stroke.set"; let st = self.active()?; if st.selected_symbol_part().is_some() { @@ -514,16 +540,14 @@ impl Session { let n = st.doc.node(*id)?; let row = each?.resolve(&n.appearance, false, C).ok()?; if row.is_none() && matches!(n.kind, NodeKind::Text(_)) { + if skip_type { + continue; + } return None; } - strokes.push(n.appearance.stroke_at(row).filter(|s| s.brush.is_some())?); + strokes.push(n.appearance.stroke_at(row)); } - if strokes.is_empty() { - return None; - } - // The library is read only when every stroke names a brush. - let lib = vectorcraft_brush::library(&st.doc); - strokes.iter().all(|s| vectorcraft_brush::keeps_brush_size(&lib, s)).then(|| strokes.iter().any(|s| s.profile.is_some())) + Some(strokes) } } diff --git a/crates/engine/src/tests/appearance.rs b/crates/engine/src/tests/appearance.rs index a04bb89b4a..10614deef2 100644 --- a/crates/engine/src/tests/appearance.rs +++ b/crates/engine/src/tests/appearance.rs @@ -253,6 +253,39 @@ fn brushed_strokes_profiled_reads_the_strokes_stroke_set_edits() { assert_eq!(s.brushed_strokes_profiled(), None, "an object without a stroke row takes a plain stroke"); } +/// `edited_strokes_profiled` reads the same strokes, with or without a brush: one profiled member +/// counts, and a group's own uniform stroke, which `stroke.set` edits instead, hides its members' +/// profiles. With an object without a stroke row among the targets the answer is false, since a +/// profile from `stroke.set` would give that object a plain stroke. Type without an Appearance row +/// is left out. +#[test] +fn edited_strokes_profiled_reads_the_strokes_stroke_set_edits() { + let mut s = session(); + let (a, b) = (rect(&mut s, 100.0), rect(&mut s, 250.0)); + run(&mut s, "select.set", json!({"ids": [a.0, b.0]})); + assert!(!s.edited_strokes_profiled(), "neither has a profile"); + run(&mut s, "stroke.set", json!({"ids": [b.0], "profile": "lens"})); + run(&mut s, "select.set", json!({"ids": [a.0, b.0]})); + assert!(s.edited_strokes_profiled(), "the second one has a profile"); + let g = NodeId(run(&mut s, "object.group", json!({"ids": [a.0, b.0]}))["id"].as_u64().unwrap()); + run(&mut s, "select.set", json!({"ids": [g.0]})); + assert!(s.edited_strokes_profiled(), "a group without its own stroke: its members'"); + run(&mut s, "appearance.addStroke", json!({"ids": [g.0]})); + run(&mut s, "select.set", json!({"ids": [g.0]})); + assert!(!s.edited_strokes_profiled(), "the group's own uniform stroke"); + let c = rect(&mut s, 400.0); + run(&mut s, "appearance.removeItem", json!({"ids": [c.0], "index": 1})); + run(&mut s, "select.set", json!({"ids": [b.0]})); + assert!(s.edited_strokes_profiled(), "the profiled member alone"); + run(&mut s, "select.set", json!({"ids": [b.0, c.0]})); + assert!(!s.edited_strokes_profiled(), "an object without a stroke row"); + let t = NodeId(run(&mut s, "text.create", json!({"x": 10, "y": 50, "text": "Hi"}))["id"].as_u64().unwrap()); + run(&mut s, "select.set", json!({"ids": [t.0, b.0]})); + assert!(s.edited_strokes_profiled(), "type is left out"); + run(&mut s, "select.set", json!({"ids": []})); + assert!(!s.edited_strokes_profiled(), "nothing selected"); +} + /// A compound shape's own stroke is the one `stroke.set` edits: brushed members do not count. #[test] fn brushed_strokes_profiled_reads_a_compound_shapes_own_stroke() { diff --git a/crates/ui-egui/src/panels/properties.rs b/crates/ui-egui/src/panels/properties.rs index 10e2236a60..3c9015d970 100644 --- a/crates/ui-egui/src/panels/properties.rs +++ b/crates/ui-egui/src/panels/properties.rs @@ -999,13 +999,35 @@ fn effect_delete(app: &mut VectorcraftApp, ui: &mut Ui, id: vectorcraft_doc::Nod } } +/// Whether a stroke that `stroke.set` edits has a width profile +/// ([`vectorcraft_engine::Session::edited_strokes_profiled`]), cached per document revision and +/// active Appearance row. False while the Type tool edits text or the Live Paint Bucket is active, +/// when the list edits the stroke the panel shows. +fn edited_strokes_profiled(app: &VectorcraftApp, ctx: &egui::Context) -> bool { + if super::character::text_editing(app).is_some() || app.session.bucket_paints() { + return false; + } + let Some(st) = app.session.active() else { return false }; + let key = (st.uid, st.revision, app.session.appearance_item()); + match pstate::), bool)>>(ctx, "props-edited-profiled") { + Some((k, v)) if k == key => v, + _ => { + let v = app.session.edited_strokes_profiled(); + set_pstate(ctx, "props-edited-profiled", Some((key, v))); + v + } + } +} + /// The stroke's Variable Width Profile (the Control bar's list), shown while the Width tool is in /// use or the stroke has a variable width, as the Properties panel overview places it /// (). +/// The row also shows when the shown stroke is uniform and another stroke the list edits has a +/// variable width ([`edited_strokes_profiled`]), so that Uniform can remove it. fn width_profile_row(app: &mut VectorcraftApp, ui: &mut Ui) { let stroke = super::current_stroke(app); let profile = stroke.as_ref().and_then(|s| s.profile.as_ref()); - if app.session.tool_id() != "width" && WidthProfile::id_of(profile) == "uniform" { + if app.session.tool_id() != "width" && WidthProfile::id_of(profile) == "uniform" && !edited_strokes_profiled(app, ui.ctx()) { return; } ui.horizontal(|ui| { diff --git a/crates/ui-egui/src/panels/properties/tests.rs b/crates/ui-egui/src/panels/properties/tests.rs index 62ee3f0c18..34e6ac550e 100644 --- a/crates/ui-egui/src/panels/properties/tests.rs +++ b/crates/ui-egui/src/panels/properties/tests.rs @@ -1535,6 +1535,46 @@ fn the_width_profile_of_a_brushed_stroke_offers_only_uniform() { assert_eq!(profile, None); } +/// Two selected strokes, the shown one uniform and the other with a variable width: the Width +/// Profile row still shows, and its Uniform removes the other stroke's profile. With brushes on both +/// strokes the list holds only Uniform. Once both are uniform the row is hidden again. +#[test] +fn the_width_profile_shows_while_another_selected_stroke_has_a_variable_width() { + for brushed in [false, true] { + let mut app = new_app(); + let a = app.run("shape.line", json!({"x1": 20, "y1": 100, "x2": 300, "y2": 100})).unwrap()["id"].clone(); + let b = app.run("shape.line", json!({"x1": 20, "y1": 160, "x2": 300, "y2": 160})).unwrap()["id"].clone(); + app.run("select.set", json!({"ids": [b]})).unwrap(); + app.run("stroke.set", json!({"profile": "lens"})).unwrap(); + if brushed { + app.run("brush.apply", json!({"ids": [a, b], "name": "3 pt. Round"})).unwrap(); + } + app.run("select.set", json!({"ids": [a, b]})).unwrap(); + assert_eq!(super::super::current_stroke(&app).and_then(|s| s.profile), None, "the shown stroke is uniform"); + let ctx = egui::Context::default(); + let texts = tall(&mut app, &ctx, vec![]); + assert!(shows(&texts, "Profile:"), "brushed {brushed}: {texts:?}"); + let spacing = ctx.global_style().spacing.item_spacing.x; + let texts = press(&mut app, &ctx, text_at(&texts, "Profile:").right_center() + vec2(spacing + 50.0, 0.0)); + assert_eq!(shows(&texts, "Taper Start"), !brushed, "{texts:?}"); + press(&mut app, &ctx, text_at(&texts, "Uniform").center()); + let profile = app + .session + .active() + .unwrap() + .doc + .node(vectorcraft_doc::NodeId(b.as_u64().unwrap())) + .unwrap() + .appearance + .stroke() + .unwrap() + .profile + .clone(); + assert_eq!(profile, None, "brushed {brushed}"); + assert!(!shows(&tall(&mut app, &ctx, vec![]), "Profile:"), "brushed {brushed}: every stroke is uniform"); + } +} + /// With Direct Selection, a path whose corner is selected shows that corner's kind and radius; /// each edit sets that corner alone in one undo step. Not with the Selection tool, nor with the /// whole path selected; a live rectangle keeps its own Corner Radius row instead. From a3cb54a73dcd031d8274cea5963016e57b92a3f2 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 20 Nov 2026 18:54:54 -0800 Subject: [PATCH 017/151] Panels: float geometry resizes only whole native windows Follow-up to #8411. `window.panel.float` with `group: true` on one entry of an accordion no longer resizes the accordion's native window; the entry floats into a window of its own, as it does when the window is drawn. A tab group given geometry before the main window reports its origin keeps its native window, and the queued geometry applies to that window instead of being dropped. The queued geometry only moves or resizes the window. Panels hidden with `window.panels` after the command stay hidden. The `window.panel.float` description and docs/mcp.md show `onto` and the geometry fields as separate forms, and say that a panel sharing a native window floats into a new window while the shared window keeps its other panels. --- crates/mcp/src/ui_catalog.rs | 2 +- crates/ui-egui/src/menus/ui_commands.rs | 2 +- crates/ui-egui/src/panel_docking.rs | 11 +++- .../ui-egui/src/panel_docking/native_tests.rs | 55 +++++++++++++++++++ docs/mcp.md | 10 +++- 5 files changed, 74 insertions(+), 6 deletions(-) diff --git a/crates/mcp/src/ui_catalog.rs b/crates/mcp/src/ui_catalog.rs index c3dbf78293..67572d1e21 100644 --- a/crates/mcp/src/ui_catalog.rs +++ b/crates/mcp/src/ui_catalog.rs @@ -772,7 +772,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "window.panel.float", "Float Panel", "", - "{panel: id or \"tools\", x?, y?, width?, height?, group?: bool, column?: bool or n, onto?: id, above?: id, below?: id, collapsed?: bool} float a panel (with `group`, its whole group; with `column`, its whole dock column or floating window) as a floating window with its top-left corner at x, y in window points (default: inside the dock area, cascaded), as dragging its tab out does; a whole floating window keeps its rect unless given one. Supplied geometry also moves or resizes an existing native window; omitted components keep their current values. `onto` makes it a tab of the floating group holding that panel instead; `above` / `below` a group of its own above or below the group holding that panel, in its floating window or dock column. `collapsed` then minimizes (true) or restores (false) its window or group. A hidden panel shows first. \"tools\" floats the Tools panel at x, y. Returns {layout, closed, floating}", + "{panel: id or \"tools\", x?, y?, width?, height?, group?: bool, column?: bool or n, onto?: id, above?: id, below?: id, collapsed?: bool} float a panel (with `group`, its whole group; with `column`, its whole dock column or floating window) as a floating window with its top-left corner at x, y in window points (default: inside the dock area, cascaded), as dragging its tab out does; a whole floating window keeps its rect unless given one. Supplied geometry also moves or resizes an existing native window when the float takes the whole window (a panel alone in it, `column`, or `group` on a tab group that fills it); omitted components keep their current values. A panel that shares its native window floats into a new window instead, and the shared window keeps its other panels. `onto` makes it a tab of the floating group holding that panel instead; `above` / `below` a group of its own above or below the group holding that panel, in its floating window or dock column. `collapsed` then minimizes (true) or restores (false) its window or group. A hidden panel shows first. \"tools\" floats the Tools panel at x, y. Returns {layout, closed, floating}", ), ( "window.panel.dock", diff --git a/crates/ui-egui/src/menus/ui_commands.rs b/crates/ui-egui/src/menus/ui_commands.rs index d2c72aae40..67d58232e9 100644 --- a/crates/ui-egui/src/menus/ui_commands.rs +++ b/crates/ui-egui/src/menus/ui_commands.rs @@ -773,7 +773,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "window.panel.float", "Float Panel", "", - "{panel: id or \"tools\", x?, y?, width?, height?, group?: bool, column?: bool or n, onto?: id, above?: id, below?: id, collapsed?: bool} float a panel (with `group`, its whole group; with `column`, its whole dock column or floating window) as a floating window with its top-left corner at x, y in window points (default: inside the dock area, cascaded), as dragging its tab out does; a whole floating window keeps its rect unless given one. Supplied geometry also moves or resizes an existing native window; omitted components keep their current values. `onto` makes it a tab of the floating group holding that panel instead; `above` / `below` a group of its own above or below the group holding that panel, in its floating window or dock column. `collapsed` then minimizes (true) or restores (false) its window or group. A hidden panel shows first. \"tools\" floats the Tools panel at x, y. Returns {layout, closed, floating}", + "{panel: id or \"tools\", x?, y?, width?, height?, group?: bool, column?: bool or n, onto?: id, above?: id, below?: id, collapsed?: bool} float a panel (with `group`, its whole group; with `column`, its whole dock column or floating window) as a floating window with its top-left corner at x, y in window points (default: inside the dock area, cascaded), as dragging its tab out does; a whole floating window keeps its rect unless given one. Supplied geometry also moves or resizes an existing native window when the float takes the whole window (a panel alone in it, `column`, or `group` on a tab group that fills it); omitted components keep their current values. A panel that shares its native window floats into a new window instead, and the shared window keeps its other panels. `onto` makes it a tab of the floating group holding that panel instead; `above` / `below` a group of its own above or below the group holding that panel, in its floating window or dock column. `collapsed` then minimizes (true) or restores (false) its window or group. A hidden panel shows first. \"tools\" floats the Tools panel at x, y. Returns {layout, closed, floating}", ), ( "window.panel.dock", diff --git a/crates/ui-egui/src/panel_docking.rs b/crates/ui-egui/src/panel_docking.rs index fb0ab20a30..f3f6c25489 100644 --- a/crates/ui-egui/src/panel_docking.rs +++ b/crates/ui-egui/src/panel_docking.rs @@ -867,7 +867,8 @@ fn native_float_geometry(app: &VectorcraftApp, command: &mut DockCommand return None; } let window = floating_window(layout, panel)?; - let whole = *column || window.panels().count() == 1 || (*group && matches!(window.root, Node::Tabs { .. } | Node::Stack { .. })); + // A group of an accordion (`Node::Stack`) is its one entry, which floats into a window of its own. + let whole = *column || window.panels().count() == 1 || (*group && matches!(window.root, Node::Tabs { .. })); if !whole { return None; } @@ -901,6 +902,11 @@ fn native_float_geometry(app: &VectorcraftApp, command: &mut DockCommand fields.insert(name.into(), json!(value)); } } + // A tab group given a rect floats as a new window without its native rect; without one it + // keeps the window, and the replay applies the geometry. + if *group && !*column { + [*x, *y, *width, *height] = [None; 4]; + } return Some(NativeFloatGeometry::Deferred { window: window.id, params }); }; // Native windows report desktop coordinates; float commands use the main window's points. @@ -1229,9 +1235,12 @@ pub(crate) fn show(app: &mut VectorcraftApp, ui: &mut egui::Ui) { // The original panel may have docked while other panels kept this native window. fields.insert("panel".into(), json!(panel)); fields.insert("column".into(), json!(true)); + // Only the geometry: panels hidden since the command stay hidden. + let (dock, raise) = (app.ui.dock, app.dock_rt.raise.clone()); if let Err(error) = shared_command(app, "window.panel.float", ¶ms) { app.ui.status = error; } + (app.ui.dock, app.dock_rt.raise) = (dock, raise); } } crate::tools_float::set_dock_area_left(&ctx, ui.available_rect_before_wrap().left()); diff --git a/crates/ui-egui/src/panel_docking/native_tests.rs b/crates/ui-egui/src/panel_docking/native_tests.rs index e9e8c4a3df..768ad623ff 100644 --- a/crates/ui-egui/src/panel_docking/native_tests.rs +++ b/crates/ui-egui/src/panel_docking/native_tests.rs @@ -358,6 +358,61 @@ fn saved_native_geometry_updates_before_viewport_metadata_is_available() { assert_eq!(h.host.borrow().windows[&viewport].rect.min, ORIGIN + vec2(480.0, 260.0)); } +/// Swatches and Color as tabs of one native window, with its OS window drawn. +fn native_tab_group(h: &mut Harness) -> ViewportId { + let viewport = h.float("swatches"); + h.app.run("window.panel.float", json!({"panel": "color", "onto": "swatches"})).unwrap(); + h.frames(3); + assert_eq!(h.viewport("color"), viewport); + viewport +} + +#[test] +fn a_deferred_group_float_of_one_accordion_entry_leaves_the_accordion_window_alone() { + let mut h = Harness::new(); + let viewport = native_tab_group(&mut h); + let mut layout = layout_of(&h.app.ui); + let entry = |panel: &str| craft_ui::docking::StackEntry { panel: panel.to_string(), open: true, height: None }; + layout.floating.iter_mut().find(|w| w.contains(&"swatches".to_string())).unwrap().root = + Node::Stack { entries: vec![entry("swatches"), entry("color")] }; + h.app.ui.docking = Some(layout); + h.frames(3); + let before = h.host.borrow().windows[&viewport].rect; + h.app.ui_ctx = None; + h.app.run("window.panel.float", json!({"panel": "swatches", "group": true, "width": 400})).unwrap(); + h.frames(3); + assert_eq!(h.viewport("color"), viewport); + assert_ne!(h.viewport("swatches"), viewport, "the entry floats in a window of its own"); + assert_eq!(h.host.borrow().windows[&viewport].rect, before, "the accordion's window keeps its place and size"); +} + +#[test] +fn a_deferred_group_float_of_a_tab_group_resizes_its_native_window() { + let mut h = Harness::new(); + let viewport = native_tab_group(&mut h); + let id = floating_window(&layout_of(&h.app.ui), "swatches").unwrap().id; + let before = h.host.borrow().windows[&viewport].rect; + h.app.ui_ctx = None; + h.app.run("window.panel.float", json!({"panel": "swatches", "group": true, "width": 400})).unwrap(); + h.frames(3); + assert_eq!(floating_window(&layout_of(&h.app.ui), "swatches").unwrap().id, id); + assert_eq!(h.viewport("color"), viewport); + assert_eq!(h.host.borrow().windows[&viewport].rect, Rect::from_min_size(before.min, vec2(400.0, before.height()))); +} + +#[test] +fn deferred_native_geometry_does_not_show_panels_hidden_before_it_applies() { + let mut h = Harness::new(); + h.float("swatches"); + h.app.ui_ctx = None; + h.app.run("window.panel.float", json!({"panel": "swatches", "width": 350})).unwrap(); + h.app.run("window.panels", json!({})).unwrap(); + assert!(!h.app.ui.dock); + h.frames(3); + assert!(!h.app.ui.dock, "the panels stay hidden"); + assert_eq!(floating_window(&layout_of(&h.app.ui), "swatches").and_then(|w| w.native).map(|n| n[2]), Some(350.0)); +} + #[test] fn a_floated_panel_opens_its_own_os_window_where_the_backend_has_viewports() { let mut h = Harness::new(); diff --git a/docs/mcp.md b/docs/mcp.md index 3cb8d1d239..ca9a95037e 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -5935,9 +5935,13 @@ and several can be open at once. `window.swatchLibrary {library}`, `window.graph `{open, panel, name, count}`; `library: null` closes every panel of that kind. The panel id is `library::` (`library:swatches:pastels`, `library:graphicStyles:hand-drawn`, `library:swatches:loaded/C:/Palettes/Brand.ase`), and the panel commands take it like any other panel's: -`window.panel.float {panel, onto?, x?, y?, width?, height?}` groups, moves or resizes it. Supplied -geometry also updates an existing native panel window. Positions are relative to the main window's -content origin; omitted coordinates and dimensions keep the native window's current values. +`window.panel.float {panel, onto}` makes it a tab of the floating group holding `onto`, and +`window.panel.float {panel, x?, y?, width?, height?}` moves or resizes it; `onto` takes no geometry. +Positions are relative to the main window's content origin. When the panel is alone in a native panel +window, or `column: true` (or `group: true` on a tab group that fills the window) names the whole window, +supplied geometry updates that window and omitted coordinates and dimensions keep its current values. +A panel that shares a native window with other panels floats into a new window instead, which takes the +supplied geometry, and the shared window keeps the other panels, its place and its size. `window.panel.dock {panel}` docks it, `window.panel.close {panel}` closes it. `window.swatchLibrary.other {path}`, `window.graphicStyleLibrary.other {path}`, `window.symbolLibrary.other {path}` and `window.brushLibrary.other {path}` load a file and open it the same From 54dda6fd2faf19ebebd7ad133ed4c0a43362dd63 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 20 Nov 2026 20:41:58 -0800 Subject: [PATCH 018/151] Canvas: a tool drag ends with the modifiers held at its button release The canvas sent a tool's Up event the release event's position but the frame's modifiers. A click released with Shift held, and Shift let go in the same frame, counted as a release without Shift: the Tangent Circle Tool, for one, then drew a circle where Shift at the release draws none. The Up event, and the Zoom tool's click, now take the modifiers from the button release event, and the frame's modifiers when the frame has no release event. --- crates/ui-egui/src/canvas/input.rs | 16 ++++++++++++++-- crates/ui-egui/src/canvas/tests.rs | 30 ++++++++++++++++++++++++++++++ 2 files changed, 44 insertions(+), 2 deletions(-) diff --git a/crates/ui-egui/src/canvas/input.rs b/crates/ui-egui/src/canvas/input.rs index a6a0509de5..67391b2e6e 100644 --- a/crates/ui-egui/src/canvas/input.rs +++ b/crates/ui-egui/src/canvas/input.rs @@ -139,8 +139,10 @@ pub(super) fn handle_input(app: &mut VectorcraftApp, ui: &Ui, resp: &egui::Respo if held { drag_held(app, ui, &f, d, p); } else { - // The drag ends where its button went up: the moves after the release in this frame are hover. - drag_released(app, ui, &f, d, release_pos(ui, button, false).unwrap_or(p)); + // The drag ends where its button went up, with the modifiers held then: the moves and + // modifier changes after the release in this frame do not count. + let up = Pointing { m: release_mods(ui, button).unwrap_or(f.m), ..f }; + drag_released(app, ui, &up, d, release_pos(ui, button, false).unwrap_or(p)); } } else if let Some(p) = hover_tool // A press on an artboard's name starts no drag: the moves while it is held are not hover. @@ -744,6 +746,16 @@ fn release_pos(ui: &Ui, button: egui::PointerButton, last: bool) -> Option }) } +/// The modifiers held when `button` first went up in this frame, the release that ends a drag. +fn release_mods(ui: &Ui, button: egui::PointerButton) -> Option { + ui.input(|i| { + i.events.iter().find_map(|e| match e { + egui::Event::PointerButton { button: b, pressed: false, modifiers, .. } if *b == button => Some(*modifiers), + _ => None, + }) + }) +} + /// Whether Space moves the Zoom tool's marquee in the drag under way ([`zoom_marquee_start`]). fn zoom_space_free_id() -> egui::Id { egui::Id::unique("canvas-zoom-space-free") diff --git a/crates/ui-egui/src/canvas/tests.rs b/crates/ui-egui/src/canvas/tests.rs index d5244aa234..cc4660f7bf 100644 --- a/crates/ui-egui/src/canvas/tests.rs +++ b/crates/ui-egui/src/canvas/tests.rs @@ -1421,6 +1421,36 @@ fn shift_clicking_canvas_artboard_label_toggles_multi_selection() { assert_eq!(app.session.tool_options()["selected"], json!([2]), "Plain click selects that artboard alone"); } +/// A tool drag ends with the modifiers held when its button went up. Shift let go after the +/// release in the same frame still constrains the Rectangle tool's last rectangle to a square, and +/// Shift pressed after the release does not constrain it. +#[test] +fn tool_drag_ends_with_the_modifiers_of_its_button_release() { + let draw = |held: egui::Modifiers, after: egui::Modifiers| { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.session.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + app.select_tool("rectangle"); + let ctx = egui::Context::default(); + frame(&mut app, &ctx, vec![]); + let from = app.canvas_rect.unwrap().center() - vec2(30.0, 15.0); + let to = from + vec2(60.0, 30.0); + let b = |pos, pressed| egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers: held }; + frame(&mut app, &ctx, vec![egui::Event::ModifiersChanged(held), egui::Event::PointerMoved(from), b(from, true)]); + frame(&mut app, &ctx, vec![egui::Event::PointerMoved(from + vec2(30.0, 15.0))]); + frame(&mut app, &ctx, vec![egui::Event::PointerMoved(to), b(to, false), egui::Event::ModifiersChanged(after)]); + frame(&mut app, &ctx, vec![egui::Event::ModifiersChanged(egui::Modifiers::NONE)]); + let st = app.session.active().unwrap(); + let kids = st.doc.layers[0].children().unwrap(); + assert_eq!(kids.len(), 1, "the drag draws one rectangle"); + let b = kids[0].geometric_bounds().unwrap(); + (b.width(), b.height()) + }; + let (w, h) = draw(egui::Modifiers::SHIFT, egui::Modifiers::NONE); + assert!((w - h).abs() < 1e-6, "Shift held at the release draws a square, got {w} x {h}"); + let (w, h) = draw(egui::Modifiers::NONE, egui::Modifiers::SHIFT); + assert!((w - 2.0 * h).abs() < 1e-6, "Shift pressed after the release does not constrain, got {w} x {h}"); +} + /// A press on an artboard's name starts no drag. Moving with the button still held is not hover, /// so Shift over a gridline intersection does not position the Perspective Selection tool's plane /// until the button is up. From a1c46996c213a6198fb338f9df65bf5a44067e0e Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 20 Nov 2026 20:46:59 -0800 Subject: [PATCH 019/151] Place: file.place without the dialog applies the PDF Text preference to an embedded PDF file.place run as a command (MCP, scripts in the app) applied the pdfTextAs preference only to places the user started, so an embedded PDF placed with showImportOptions: false and no textAs kept its text as point type even with PDF Text set to Outlines. docs/mcp.md says such a place takes the preference. The command path now applies it the same way: a textAs given with the place, a linked place and a .ai file keep their own text. --- crates/ui-egui/src/dialogs/import_pdf.rs | 4 +-- .../ui-egui/src/dialogs/tests_import_pdf.rs | 34 +++++++++++++++++++ crates/ui-egui/src/place.rs | 6 ++-- 3 files changed, 39 insertions(+), 5 deletions(-) diff --git a/crates/ui-egui/src/dialogs/import_pdf.rs b/crates/ui-egui/src/dialogs/import_pdf.rs index b14cba49cd..c28f5694f6 100644 --- a/crates/ui-egui/src/dialogs/import_pdf.rs +++ b/crates/ui-egui/src/dialogs/import_pdf.rs @@ -264,8 +264,8 @@ pub(crate) fn with_preferred_text_as(app: &VectorcraftApp, name: &str, bytes: &[ p } -/// The `file.place` params `p` of a PDF the user places embedded (Link off, from bytes or with a -/// password) get the `pdfTextAs` preference as their `textAs` when it is Outlines and they have no +/// The `file.place` params `p` of a PDF placed embedded (Link off, from bytes or with a password), +/// by the user or as a command, get the `pdfTextAs` preference as their `textAs` when it is Outlines and they have no /// `textAs`. A linked page shows the file's own text, and a `.ai` or `.ait` file is placed as it /// says. pub(crate) fn place_with_preferred_text_as(app: &VectorcraftApp, p: &mut Value) { diff --git a/crates/ui-egui/src/dialogs/tests_import_pdf.rs b/crates/ui-egui/src/dialogs/tests_import_pdf.rs index 06bdf5e1b7..a1e9a350a4 100644 --- a/crates/ui-egui/src/dialogs/tests_import_pdf.rs +++ b/crates/ui-egui/src/dialogs/tests_import_pdf.rs @@ -491,3 +491,37 @@ fn the_text_choice_applies_to_embedded_places_only() { assert!(!matches!(placed.kind, NodeKind::PlacedDocument(_)), "embedded: {:?}", placed.kind); assert_eq!(type_objects(&app), before, "placed as outlines"); } + +/// `file.place` run as a command (MCP, scripts) without the dialog takes the PDF Text preference for +/// an embedded PDF with no `textAs`, as a place by the user does; a `textAs` given and a linked +/// place keep their own text. +#[test] +fn file_place_without_the_dialog_takes_the_pdf_text_preference() { + let mut app = app(); + set_pdf_text(&mut app, "outlines"); + let dir = vectorcraft_testkit::TempDir::new("import-pdf-text-at-once"); + let path = dir.join("two.pdf").to_string_lossy().into_owned(); + std::fs::write(&path, text_pages(2)).unwrap(); + let embedded = json!({"path": path, "link": false, "showImportOptions": false}); + crate::place::run(&mut app, &embedded).unwrap(); + assert!(app.ui.dialog.is_none(), "no dialog"); + assert_eq!(type_objects(&app), 0, "the preference: outlines"); + + let one = json!({"name": "one.pdf", "dataBase64": vectorcraft_format::base64_encode(&text_pages(1))}); + crate::place::run(&mut app, &one).unwrap(); + assert_eq!(type_objects(&app), 0, "one page from bytes: outlines"); + + let mut given = embedded.clone(); + given["textAs"] = json!("text"); + crate::place::run(&mut app, &given).unwrap(); + assert_eq!(type_objects(&app), 1, "a textAs given is kept"); + + crate::place::run(&mut app, &json!({"path": path, "showImportOptions": false})).unwrap(); + let st = app.session.active().unwrap(); + let placed = st.doc.node(st.selection.objects[0]).unwrap(); + assert!(matches!(placed.kind, NodeKind::PlacedDocument(_)), "linked: {:?}", placed.kind); + + set_pdf_text(&mut app, "text"); + crate::place::run(&mut app, &embedded).unwrap(); + assert_eq!(type_objects(&app), 2, "Editable: page 1's type object"); +} diff --git a/crates/ui-egui/src/place.rs b/crates/ui-egui/src/place.rs index a36d85f8a2..4e8107cc12 100644 --- a/crates/ui-egui/src/place.rs +++ b/crates/ui-egui/src/place.rs @@ -262,9 +262,9 @@ fn place_file_in(app: &mut VectorcraftApp, p: &Value, read: Read) -> Result { let r = crate::placing::start(app, &p, dropped); From d00e25c9622b5adb540c962df28415c761a5c1eb Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 20 Nov 2026 17:37:47 -0800 Subject: [PATCH 020/151] Paste on All Artboards: swatch conflicts leave copied artboard backgrounds out Paste on All Artboards leaves copied artboards behind, so it does not convert their background colors: edit.paste passes the boards only in the other paste modes, and clipboard.profileMismatch takes allArtboards for the same reason. clipboard.conflicts always counted the backgrounds. When only a copied artboard's background had another profile, it treated the paste as converting and listed the swatches the document had edited since the copy, so Swatch Conflict asked about swatches while the paste itself converted nothing. - clipboard.conflicts takes allArtboards (true or false, default false; other values are refused). With true it lists the conflicts as Paste on All Artboards brings the colors, without the copied artboards' backgrounds. - The Swatch Conflict dialog passes allArtboards: true when the paste it asks about is edit.pasteOnAllArtboards. - Params text and docs/mcp.md describe the parameter. --- crates/engine/src/cmd/clipboard.rs | 9 ++++-- crates/engine/tests/color_settings.rs | 31 +++++++++++++++++++ .../src/dialogs/profile_mismatch/tests.rs | 25 +++++++++++++++ crates/ui-egui/src/dialogs/swatch_conflict.rs | 14 ++++++--- docs/mcp.md | 3 +- 5 files changed, 73 insertions(+), 9 deletions(-) diff --git a/crates/engine/src/cmd/clipboard.rs b/crates/engine/src/cmd/clipboard.rs index c6c1da2980..610498f56a 100644 --- a/crates/engine/src/cmd/clipboard.rs +++ b/crates/engine/src/cmd/clipboard.rs @@ -47,7 +47,7 @@ pub fn specs() -> Vec { "Swatch Conflicts", [], None, - "{profileMismatch?: as edit.paste} → {swatches: [{name, document, clipboard, spot}]} the global or spot swatches the copied objects use whose name the active document gives another colour (`document`/`clipboard`: #rrggbb, the pasted colour as the paste brings it, converted when profileMismatch or the policy converts it): Paste asks Merge or Add for each (pass the answer as edit.paste* {swatchConflict}). Pasting back into the document the objects came from raises none, unless the paste converts its colours", + "{profileMismatch?: as edit.paste, allArtboards?: false (true: for edit.pasteOnAllArtboards, which leaves the background colors of copied artboards behind)} → {swatches: [{name, document, clipboard, spot}]} the global or spot swatches the copied objects use whose name the active document gives another colour (`document`/`clipboard`: #rrggbb, the pasted colour as the paste brings it, converted when profileMismatch or the policy converts it): Paste asks Merge or Add for each (pass the answer as edit.paste* {swatchConflict}). Pasting back into the document the objects came from raises none, unless the paste converts its colours", has_doc, conflicts ), @@ -568,9 +568,12 @@ fn import_svg(s: &mut Session, p: &Value) -> Result { fn conflicts(s: &mut Session, p: &Value) -> Result { let hex = |w: &Swatch| w.paint.color().map(|c| c.to_hex()); // The swatches as the paste brings them: converted from another profile when it converts. - let profile = super::colormgmt::PasteProfile::param(p, "clipboard.conflicts")?; + const CMD: &str = "clipboard.conflicts"; + let profile = super::colormgmt::PasteProfile::param(p, CMD)?; + // Paste on All Artboards leaves the copied artboards, and so their backgrounds, behind. + let all_artboards = super::switch_or(p, "allArtboards", false, CMD)?; let st = s.doc()?; - let (converted, _) = super::colormgmt::paste_profiles(&s.clipboard, &st.doc, profile, true); + let (converted, _) = super::colormgmt::paste_profiles(&s.clipboard, &st.doc, profile, !all_artboards); let list: Vec = converted .as_ref() .unwrap_or(&s.clipboard) diff --git a/crates/engine/tests/color_settings.rs b/crates/engine/tests/color_settings.rs index c07d741265..4888c3ae25 100644 --- a/crates/engine/tests/color_settings.rs +++ b/crates/engine/tests/color_settings.rs @@ -1767,6 +1767,37 @@ fn paste_on_all_artboards_leaves_artboard_backgrounds_out() { assert!(r.get("profileMismatch").is_none(), "{r}"); } +/// The swatch conflicts Paste on All Artboards raises leave copied artboard backgrounds out, as the +/// paste does: pasting back into the document the objects came from, where only the RGB background +/// of the copied artboard now has another profile, converts nothing for it, so its edited CMYK +/// swatch raises no conflict. A plain paste, which brings the background and converts it, compares +/// the swatches and lists the edited one. +#[test] +fn swatch_conflicts_on_all_artboards_leave_artboard_backgrounds_out() { + let _g = settings(); + let _reset = ColorSettingsReset { profile: None, paths: vec![] }; + let mut s = session(); + exec(&mut s, "swatch.new", json!({"name": "Brand", "color": {"c": 20, "m": 40, "y": 60, "k": 10}, "global": true})); + let ink = rect(&mut s, 0.0, 0.0, 10.0, 10.0); + exec(&mut s, "paint.setFill", json!({"ids": [ink.0], "swatch": "Brand"})); + exec(&mut s, "paint.setStroke", json!({"ids": [ink.0], "none": true})); + exec(&mut s, "artboard.setProps", json!({"index": 0, "color": "#3366cc"})); + exec(&mut s, "edit.assignProfile", json!({"rgb": cms::WIDE_GAMUT_RGB})); + exec(&mut s, "artboard.copy", json!({"index": 0})); + exec(&mut s, "edit.assignProfile", json!({"rgb": null})); + exec(&mut s, "swatch.edit", json!({"name": "Brand", "color": {"c": 60, "m": 40, "y": 20, "k": 0}})); + let conflicts = |s: &mut Session, p: serde_json::Value| exec(s, "clipboard.conflicts", p)["swatches"].as_array().unwrap().len(); + assert_eq!(conflicts(&mut s, json!({"profileMismatch": "convert"})), 1, "a plain paste converts the RGB background"); + assert_eq!(conflicts(&mut s, json!({"profileMismatch": "convert", "allArtboards": true})), 0); + assert_eq!(conflicts(&mut s, json!({"profileMismatch": "convert", "allArtboards": false})), 1); + assert_eq!(conflicts(&mut s, json!({"profileMismatch": "convert", "allArtboards": null})), 1, "null is the default"); + for bad in [json!("yes"), json!(1)] { + assert!(s.execute("clipboard.conflicts", &json!({ "allArtboards": bad })).is_err(), "{bad}"); + } + let r = exec(&mut s, "edit.pasteOnAllArtboards", json!({"profileMismatch": "convert"})); + assert!(r.get("profileMismatch").is_none(), "{r}"); +} + /// A converting paste back into the document the objects came from (its profile changed since the /// copy) still takes its image blobs as the document's own: an image whose blob under its key /// changed since keeps that key, and so shows the document's blob. diff --git a/crates/ui-egui/src/dialogs/profile_mismatch/tests.rs b/crates/ui-egui/src/dialogs/profile_mismatch/tests.rs index 358c6f428e..19b8105cf4 100644 --- a/crates/ui-egui/src/dialogs/profile_mismatch/tests.rs +++ b/crates/ui-egui/src/dialogs/profile_mismatch/tests.rs @@ -385,6 +385,7 @@ fn opening_and_pasting_ask_about_profiles() { assert_eq!(count(&app), before + 1); swatch_conflicts_are_asked_again_when_they_change(&mut app); all_artboards_leaves_backgrounds_out(&mut app); + all_artboards_asks_no_swatch_conflict_for_backgrounds(&mut app); // It changes the working space: last. app.run("edit.colorSettings", json!({"askMismatchOpen": true})).unwrap(); an_answer_waits_for_the_question_it_answers(&mut app, &tagged); @@ -410,3 +411,27 @@ fn all_artboards_leaves_backgrounds_out(app: &mut VectorcraftApp) { assert_eq!(listed(app, "edit.paste"), Some(1), "the background is RGB"); assert_eq!(listed(app, ALL_ARTBOARDS), Some(0)); } + +/// Swatch Conflict for Paste on All Artboards asks about the colors it brings, without the +/// backgrounds of copied artboards: pasting back into the document the art came from, where only +/// the RGB background now has another profile, converts nothing, so the edited CMYK swatch is no +/// conflict and the paste runs. A plain paste converts the background and asks. +fn all_artboards_asks_no_swatch_conflict_for_backgrounds(app: &mut VectorcraftApp) { + use super::super::swatch_conflict; + app.run("file.new", json!({"width": 100, "height": 100})).unwrap(); + app.run("swatch.new", json!({"name": "Brand", "color": {"c": 20, "m": 40, "y": 60, "k": 10}, "global": true})).unwrap(); + app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 20, "height": 20})).unwrap(); + app.run("paint.setFill", json!({"swatch": "Brand"})).unwrap(); + app.run("paint.setStroke", json!({"none": true})).unwrap(); + app.run("artboard.setProps", json!({"index": 0, "color": "#3366cc"})).unwrap(); + app.run("edit.assignProfile", json!({ "rgb": cms::WIDE_GAMUT_RGB })).unwrap(); + app.run("artboard.copy", json!({"index": 0})).unwrap(); + app.run("edit.assignProfile", json!({ "rgb": null })).unwrap(); + app.run("swatch.edit", json!({"name": "Brand", "color": {"c": 60, "m": 40, "y": 20, "k": 0}})).unwrap(); + let r = app.run("edit.paste", json!({"profileMismatch": "convert"})).unwrap(); + assert_eq!(r["dialog"], swatch_conflict::KIND, "{r}"); + super::super::cancel(app); + let r = app.run(ALL_ARTBOARDS, json!({"profileMismatch": "convert"})).unwrap(); + assert!(r.get("dialog").is_none() && r["ids"].as_array().is_some_and(|ids| !ids.is_empty()), "{r}"); + assert!(app.ui.dialog.is_none()); +} diff --git a/crates/ui-egui/src/dialogs/swatch_conflict.rs b/crates/ui-egui/src/dialogs/swatch_conflict.rs index 96ff733c42..b3dc56c372 100644 --- a/crates/ui-egui/src/dialogs/swatch_conflict.rs +++ b/crates/ui-egui/src/dialogs/swatch_conflict.rs @@ -36,7 +36,7 @@ pub fn ask(app: &mut VectorcraftApp, command: &str, params: &Value) -> Option DialogResult { // pasted swatches), it asks again about them instead. let asked = list.to_vec(); app.ui.dialog = None; - let changed = |app: &mut VectorcraftApp, _: &str, params: &Value| found(app, params).is_some_and(|now| now != asked); + let changed = |app: &mut VectorcraftApp, command: &str, params: &Value| found(app, command, params).is_some_and(|now| now != asked); let recheck = crate::placing::Recheck { key: "swatchConflict", changed: &changed }; let deferred = d.fields.get("__deferredPaste").and_then(Value::as_u64); crate::placing::confirm_swatch_paste(app, &d.str("__command"), params, deferred, Some(&recheck)) } -/// The swatch conflicts pasting with `params` raises (`clipboard.conflicts`), with the swatches as -/// the paste brings them: converted from another profile when it converts. -fn found(app: &mut VectorcraftApp, params: &Value) -> Option> { +/// The swatch conflicts paste `command` with `params` raises (`clipboard.conflicts`), with the +/// swatches as the paste brings them: converted from another profile when it converts, and for +/// Paste on All Artboards without the backgrounds of copied artboards, which it leaves behind. +fn found(app: &mut VectorcraftApp, command: &str, params: &Value) -> Option> { let mut q = json!({}); if let Some(m) = params.get("profileMismatch") { q["profileMismatch"] = m.clone(); } + if command == "edit.pasteOnAllArtboards" { + q["allArtboards"] = json!(true); + } let found = app.session.execute("clipboard.conflicts", &q).ok()?; found["swatches"].as_array().cloned() } diff --git a/docs/mcp.md b/docs/mcp.md index e7abf476a9..71dcaf7a11 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -9105,7 +9105,8 @@ light one, by the wedge colors as pasted: a wedge linked to a swatch merged with color first. A global or spot swatch whose name the document gives another colour is a conflict: `clipboard.conflicts` lists -them, and `swatchConflict` answers: `"merge"` (the default: the objects take the document's swatch), `"add"` (the +them (with `allArtboards: true`, the colors as Paste on All Artboards brings them, without the background colors of +copied artboards), and `swatchConflict` answers: `"merge"` (the default: the objects take the document's swatch), `"add"` (the pasted swatch comes in renamed) or one answer per name. When a merged swatch turns a pie's wedge from light to dark or back, the legend labels in that pie's wedges take the contrast a redraw gives them (white on a dark wedge, black on a light one), unless the legend labels have a fill of their own. Pasting back into the document the objects came from From 17554f2a9199311b43872bc4f858e9aa634d5666 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 20 Nov 2026 14:48:15 -0800 Subject: [PATCH 021/151] Gradient panel: a picked midpoint stays with the gradient it was picked on The Gradient panel kept a selected midpoint diamond for the first selected object only. With that object still selected, choosing the Live Paint Bucket or toggling to the Stroke proxy left the diamond selected on the gradient the panel showed then, and the Location field edited that gradient's midpoint although nobody picked it. The diamond is now kept for the same owner a selected stop is kept for (document, object, proxy, Appearance row, symbol part and the bucket), through the new `Session::gradient_owner`. --- crates/engine/src/cmd/gradient.rs | 10 ++++++-- crates/engine/src/lib.rs | 1 + crates/ui-egui/src/panels/gradient.rs | 19 ++++++--------- crates/ui-egui/src/panels/gradient/tests.rs | 27 +++++++++++++++++++++ 4 files changed, 44 insertions(+), 13 deletions(-) diff --git a/crates/engine/src/cmd/gradient.rs b/crates/engine/src/cmd/gradient.rs index 8cf1091492..43e9794f08 100644 --- a/crates/engine/src/cmd/gradient.rs +++ b/crates/engine/src/cmd/gradient.rs @@ -87,9 +87,10 @@ fn select_stop(s: &mut Session, p: &Value) -> Result { /// front, the Appearance panel's active item and whether the Live Paint Bucket is the active tool /// (its proxies show the default paint). Selecting other art, picking a part of the instance, /// toggling the proxy, picking another item or choosing the bucket or leaving it leaves no stop -/// selected. +/// selected. The Gradient panel keys its selected midpoint diamond by it as well +/// ([`Session::gradient_owner`]). #[derive(Clone, Copy, Debug, PartialEq)] -pub(crate) struct StopOwner { +pub struct StopOwner { doc: Option, object: Option, /// The object whose paint the active proxy shows: a Live Paint group without faces (or edges) @@ -134,6 +135,11 @@ impl Session { pub fn selected_stop(&self) -> Option { self.gradient_stop.filter(|(_, owner)| *owner == StopOwner::of(self)).map(|(i, _)| i) } + + /// Whose gradient the active proxy shows now, as a selected stop keeps it ([`StopOwner`]). + pub fn gradient_owner(&self) -> StopOwner { + StopOwner::of(self) + } } type Parsed = std::result::Result; diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index e2e6430f1e..5db4b136fa 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -30,6 +30,7 @@ pub use cmd::clipboard::{Clipboard, SourceLayer}; pub use cmd::create::constrain_click; pub use cmd::distortcmds::{perspective_click, width_point_pair}; pub use cmd::flare::flare_settings; +pub use cmd::gradient::StopOwner; pub use cmd::graph::{GraphTypeSubject, calculated_axes as graph_calculated_axes, graph_type_subject}; pub use cmd::params::{check_keys, check_params}; pub use cmd::pathops::auto_simplify_level; diff --git a/crates/ui-egui/src/panels/gradient.rs b/crates/ui-egui/src/panels/gradient.rs index 945c18ea0d..06ba6ca8a8 100644 --- a/crates/ui-egui/src/panels/gradient.rs +++ b/crates/ui-egui/src/panels/gradient.rs @@ -31,7 +31,8 @@ use vectorcraft_color::gradient::{ MAX_REPEATS, MIN_STOPS, duplicate_stop, insert_stop, midpoint_from_pos, midpoint_pos, move_stop, remove_stop, set_midpoint, swap_stop_colors, }; use vectorcraft_color::{Color, Freeform, FreeformMode, Gradient, GradientKind, GradientMethod, GradientPaint, GradientSpread, GradientStop, Paint}; -use vectorcraft_doc::{NodeId, StrokeGradientMode}; +use vectorcraft_doc::StrokeGradientMode; +use vectorcraft_engine::StopOwner; use super::{active_paint, live_run, pstate, set_pstate}; use crate::state::Dialog; @@ -231,15 +232,11 @@ fn gradient_swatches(app: &VectorcraftApp) -> Vec<(String, GradientPaint)> { .collect() } -/// The selected midpoint diamond: kept for the object it was picked on, and given up when a stop -/// is selected. +/// The selected midpoint diamond: kept for the gradient it was picked on, as a selected stop is +/// ([`vectorcraft_engine::Session::gradient_owner`]), and given up when a stop is selected. fn selected_mid(app: &VectorcraftApp, ctx: &egui::Context, stops: usize) -> Option { - let (i, owner) = pstate::)>>(ctx, MID_SELECTED)?; - (app.session.selected_stop().is_none() && i + 1 < stops && owner == first_id(app)).then_some(i) -} - -fn first_id(app: &VectorcraftApp) -> Option { - app.session.active().and_then(|d| d.selection.objects.first().copied()) + let (i, owner) = pstate::>(ctx, MID_SELECTED)?; + (app.session.selected_stop().is_none() && i + 1 < stops && owner == app.session.gradient_owner()).then_some(i) } // ---------- UI ---------- @@ -935,12 +932,12 @@ fn apply_ramp_edit( popover: Option<(usize, Pos2)>, ) { if let Some(i) = pick_mid { - set_pstate(ui.ctx(), MID_SELECTED, Some((i, first_id(app)))); + set_pstate(ui.ctx(), MID_SELECTED, Some((i, app.session.gradient_owner()))); if sel.is_some() { select_stop(app, None); } } else if select.is_some() { - set_pstate(ui.ctx(), MID_SELECTED, None::<(usize, Option)>); + set_pstate(ui.ctx(), MID_SELECTED, None::<(usize, StopOwner)>); } match changed { // Stops added, moved or dropped on the ramp carry colors the gradient or a swatch has, or diff --git a/crates/ui-egui/src/panels/gradient/tests.rs b/crates/ui-egui/src/panels/gradient/tests.rs index 1a607b8f24..931d87f4b7 100644 --- a/crates/ui-egui/src/panels/gradient/tests.rs +++ b/crates/ui-egui/src/panels/gradient/tests.rs @@ -1,4 +1,5 @@ use egui::{Event, Modifiers, PointerButton}; +use vectorcraft_doc::NodeId; use vectorcraft_engine::Session; use super::super::tests_long_popups::{PopupWindow, assert_last_row_scrolls_into_view, assert_short_list_does_not_scroll}; @@ -417,6 +418,32 @@ fn a_selected_diamond_shows_and_sets_its_midpoint_in_location() { assert!(texts.iter().any(|(t, _)| t == "0%")); } +/// A diamond picked on the selected object's gradient is not selected on another gradient the +/// panel shows with that object still selected: the Live Paint Bucket's, or the stroke's after the +/// proxy toggles. Going back to the object's fill selects it again. +#[test] +fn a_picked_diamond_stays_with_the_gradient_it_was_picked_on() { + let stops = json!([{"offset": 0, "color": "#ffffff", "midpoint": 0.3}, {"offset": 1, "color": "#000000"}]); + let mut app = app(json!({"gradient": {"stops": stops}})); + app.run("paint.setStroke", json!({"gradient": {"kind": "radial"}})).unwrap(); + app.session.fill_active = true; + let mut p = Panel::new(); + p.frame(&mut app, vec![], Modifiers::NONE); + let diamond = p.widget(("grad-mid", 0_usize)); + p.click(&mut app, diamond.center()); + assert_eq!(selected_mid(&app, &p.ctx, 2), Some(0), "the diamond is picked"); + app.select_tool("livePaintBucket"); + app.run("paint.setFill", json!({"gradient": {"kind": "radial"}})).unwrap(); + p.frame(&mut app, vec![], Modifiers::NONE); + assert_eq!(selected_mid(&app, &p.ctx, 2), None, "the bucket's gradient"); + app.select_tool("selection"); + p.frame(&mut app, vec![], Modifiers::NONE); + assert_eq!(selected_mid(&app, &p.ctx, 2), Some(0), "the object's fill again"); + app.session.fill_active = false; + p.frame(&mut app, vec![], Modifiers::NONE); + assert_eq!(selected_mid(&app, &p.ctx, 2), None, "the object's stroke"); +} + /// A mirrored conic's Aspect Ratio field shows the extent's size, and a typed value keeps the /// sweep mirrored. #[test] From 9965de4ec2b9f05e02cd67f45083a2d951d91c36 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 20 Nov 2026 21:27:48 -0800 Subject: [PATCH 022/151] Preferences: list the script file access kept with Always, with Revoke Preferences > General gets a Script File Access section after Show External Script Warning. It reads script.grants and shows one row for each script and path, grouped by script, with the widest access any kept version has (read file, read and write file, or read and write folder). Revoke runs script.grants.revoke for that script and path, which removes every kept version of the pair, so the next run asks again. The list is read again after a revoke, the keyboard focus moves to the row now in that place, and the status bar says whether anything was removed or shows the command's error. Paths and script names show control and bidirectional formatting characters as escapes and are cut at 1,024 characters. A grants file that is not well formed or is larger than 4 MiB makes Revoke show the error and leaves the file as it was. Without a settings folder, and on the web, the section is not shown. The rows are drawn only where they are in view, so a long list stays fast. --- crates/ui-egui/src/i18n/bg.tsv | 8 + crates/ui-egui/src/i18n/bs.tsv | 8 + crates/ui-egui/src/i18n/ca.tsv | 8 + crates/ui-egui/src/i18n/cs.tsv | 8 + crates/ui-egui/src/i18n/da.tsv | 8 + crates/ui-egui/src/i18n/de.tsv | 8 + crates/ui-egui/src/i18n/el.tsv | 8 + crates/ui-egui/src/i18n/es.tsv | 8 + crates/ui-egui/src/i18n/fi.tsv | 8 + crates/ui-egui/src/i18n/fr.tsv | 8 + crates/ui-egui/src/i18n/gu.tsv | 9 + crates/ui-egui/src/i18n/hi.tsv | 8 + crates/ui-egui/src/i18n/hu.tsv | 8 + crates/ui-egui/src/i18n/id.tsv | 8 + crates/ui-egui/src/i18n/it.tsv | 8 + crates/ui-egui/src/i18n/ja.tsv | 8 + crates/ui-egui/src/i18n/ka.tsv | 8 + crates/ui-egui/src/i18n/ko.tsv | 8 + crates/ui-egui/src/i18n/nl.tsv | 8 + crates/ui-egui/src/i18n/pl.tsv | 8 + crates/ui-egui/src/i18n/pt-br.tsv | 8 + crates/ui-egui/src/i18n/ru.tsv | 8 + crates/ui-egui/src/i18n/sv.tsv | 8 + crates/ui-egui/src/i18n/tests.rs | 35 +++ crates/ui-egui/src/i18n/tr.tsv | 8 + crates/ui-egui/src/i18n/uk.tsv | 8 + crates/ui-egui/src/i18n/vi.tsv | 8 + crates/ui-egui/src/i18n/zh-hans.tsv | 8 + crates/ui-egui/src/i18n/zh-hant.tsv | 8 + crates/ui-egui/src/prefs_dialog.rs | 6 + .../ui-egui/src/prefs_dialog/script_access.rs | 202 ++++++++++++++++++ crates/ui-egui/src/prefs_dialog/tests.rs | 174 +++++++++++++++ docs/target-app-parity.md | 1 + 33 files changed, 643 insertions(+) create mode 100644 crates/ui-egui/src/prefs_dialog/script_access.rs diff --git a/crates/ui-egui/src/i18n/bg.tsv b/crates/ui-egui/src/i18n/bg.tsv index 167737554d..090d7a66d6 100644 --- a/crates/ui-egui/src/i18n/bg.tsv +++ b/crates/ui-egui/src/i18n/bg.tsv @@ -4711,6 +4711,14 @@ axis Both И двете The script asks to read and write a folder you choose, with everything in it. Скриптът иска да чете и записва папка, която изберете, с цялото ѝ съдържание. Allow Once Разреши веднъж Always Allow This Script Винаги разрешавай този скрипт + No script has kept file access. Няма скрипт със запазен достъп до файлове. + Read file Четене на файл + Read and write file Четене и запис на файл + Read and write folder Четене и запис на папка + Revoke Отнемане + Revoke removes the access kept for every version of the script. A folder's access covers everything in it. Отнемането премахва достъпа, запазен за всяка версия на скрипта. Достъпът до папка обхваща всичко в нея. +@msg Script file access revoked Достъпът на скрипта до файлове е отнет +@msg The script file access was already revoked Достъпът на скрипта до файлове вече е отнет Deny Откажи A script can change the open documents and can write files through the commands it runs. Run only scripts you trust. Скриптът може да променя отворените документи и да записва файлове чрез командите, които изпълнява. Изпълнявайте само скриптове, на които имате доверие. Do not show this warning again Не показвай повече това предупреждение diff --git a/crates/ui-egui/src/i18n/bs.tsv b/crates/ui-egui/src/i18n/bs.tsv index a9d6e35ed8..2c4659b00c 100644 --- a/crates/ui-egui/src/i18n/bs.tsv +++ b/crates/ui-egui/src/i18n/bs.tsv @@ -5115,6 +5115,14 @@ imageTrace Outline Obris The script asks to read and write a folder you choose, with everything in it. Skripta traži da čita i piše folder koji odaberete, sa svim što je u njemu. Allow Once Dozvoli jednom Always Allow This Script Uvijek dozvoli ovu skriptu + No script has kept file access. Nijedna skripta nema sačuvan pristup datotekama. + Read file Čitanje datoteke + Read and write file Čitanje i pisanje datoteke + Read and write folder Čitanje i pisanje foldera + Revoke Opozovi + Revoke removes the access kept for every version of the script. A folder's access covers everything in it. Opozovi uklanja pristup sačuvan za svaku verziju skripte. Pristup folderu obuhvata sve u njemu. +@msg Script file access revoked Pristup skripte datotekama je opozvan +@msg The script file access was already revoked Pristup skripte datotekama je već opozvan Deny Odbij A script can change the open documents and can write files through the commands it runs. Run only scripts you trust. Skripta može mijenjati otvorene dokumente i pisati datoteke putem naredbi koje pokreće. Pokrećite samo skripte kojima vjerujete. Do not show this warning again Ne prikazuj više ovo upozorenje diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index e4271f7926..dc052e1209 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -6422,6 +6422,14 @@ digits Malayalam Malaiàlam The script asks to read and write a folder you choose, with everything in it. L’script demana llegir i escriure una carpeta que trieu, amb tot el que conté. Allow Once Permet un cop Always Allow This Script Permet sempre aquest script + No script has kept file access. Cap script no ha conservat accés als fitxers. + Read file Lectura del fitxer + Read and write file Lectura i escriptura del fitxer + Read and write folder Lectura i escriptura de la carpeta + Revoke Revoca + Revoke removes the access kept for every version of the script. A folder's access covers everything in it. Revoca elimina l’accés conservat per a cada versió de l’script. L’accés a una carpeta inclou tot el que conté. +@msg Script file access revoked S’ha revocat l’accés de l’script als fitxers +@msg The script file access was already revoked L’accés de l’script als fitxers ja s’havia revocat Deny Denega A script can change the open documents and can write files through the commands it runs. Run only scripts you trust. Un script pot canviar els documents oberts i escriure fitxers mitjançant les ordres que executa. Executeu només scripts de confiança. Do not show this warning again No tornis a mostrar aquest avís diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index 488df173c3..baa6fdb5a0 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -5230,6 +5230,14 @@ imageTrace Outline Obrys The script asks to read and write a folder you choose, with everything in it. Skript žádá o čtení a zápis složky, kterou vyberete, se vším, co obsahuje. Allow Once Povolit jednou Always Allow This Script Vždy povolit tento skript + No script has kept file access. Žádný skript nemá uložený přístup k souborům. + Read file Čtení souboru + Read and write file Čtení a zápis souboru + Read and write folder Čtení a zápis složky + Revoke Odvolat + Revoke removes the access kept for every version of the script. A folder's access covers everything in it. Odvolat odebere přístup uložený pro každou verzi skriptu. Přístup ke složce zahrnuje vše, co obsahuje. +@msg Script file access revoked Přístup skriptu k souborům byl odvolán +@msg The script file access was already revoked Přístup skriptu k souborům už byl odvolán Deny Zamítnout A script can change the open documents and can write files through the commands it runs. Run only scripts you trust. Skript může měnit otevřené dokumenty a prostřednictvím příkazů, které spouští, zapisovat soubory. Spouštějte jen skripty, kterým důvěřujete. Do not show this warning again Toto upozornění již nezobrazovat diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index 302ab6aa69..47c721d229 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -7660,6 +7660,14 @@ imageTrace Outline Kontur The script asks to read and write a folder you choose, with everything in it. Scriptet beder om at læse og skrive en mappe, du vælger, med alt indhold. Allow Once Tillad én gang Always Allow This Script Tillad altid dette script + No script has kept file access. Intet script har gemt adgang til filer. + Read file Læs fil + Read and write file Læs og skriv fil + Read and write folder Læs og skriv mappe + Revoke Tilbagekald + Revoke removes the access kept for every version of the script. A folder's access covers everything in it. Tilbagekald fjerner den adgang, der er gemt for hver version af scriptet. Adgang til en mappe omfatter alt i den. +@msg Script file access revoked Scriptets adgang til filer er tilbagekaldt +@msg The script file access was already revoked Scriptets adgang til filer var allerede tilbagekaldt Deny Afvis A script can change the open documents and can write files through the commands it runs. Run only scripts you trust. Et script kan ændre de åbne dokumenter og skrive filer gennem de kommandoer, det kører. Kør kun scripts, du stoler på. Do not show this warning again Vis ikke denne advarsel igen diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index 9482345f18..a625e018ef 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -4815,6 +4815,14 @@ theme Appearance Erscheinungsbild The script asks to read and write a folder you choose, with everything in it. Das Skript möchte einen Ordner, den Sie auswählen, mit seinem gesamten Inhalt lesen und schreiben. Allow Once Einmal erlauben Always Allow This Script Dieses Skript immer erlauben + No script has kept file access. Kein Skript hat einen gespeicherten Dateizugriff. + Read file Datei lesen + Read and write file Datei lesen und schreiben + Read and write folder Ordner lesen und schreiben + Revoke Widerrufen + Revoke removes the access kept for every version of the script. A folder's access covers everything in it. „Widerrufen“ entfernt den Zugriff, der für jede Version des Skripts gespeichert ist. Der Zugriff auf einen Ordner umfasst seinen gesamten Inhalt. +@msg Script file access revoked Dateizugriff des Skripts widerrufen +@msg The script file access was already revoked Der Dateizugriff des Skripts wurde bereits widerrufen Deny Ablehnen A script can change the open documents and can write files through the commands it runs. Run only scripts you trust. Ein Skript kann die geöffneten Dokumente ändern und über die ausgeführten Befehle Dateien schreiben. Führen Sie nur Skripte aus, denen Sie vertrauen. Do not show this warning again Diese Warnung nicht mehr anzeigen diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index 434d0cc0b8..e428decf7c 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -2619,6 +2619,14 @@ axis Both Και τα δύο The script asks to read and write a folder you choose, with everything in it. Το σενάριο ζητά να διαβάσει και να γράψει έναν φάκελο που θα επιλέξετε, με όλο το περιεχόμενό του. Allow Once Να επιτραπεί μία φορά Always Allow This Script Να επιτρέπεται πάντα αυτό το σενάριο + No script has kept file access. Κανένα σενάριο δεν έχει αποθηκευμένη πρόσβαση σε αρχεία. + Read file Ανάγνωση αρχείου + Read and write file Ανάγνωση και εγγραφή αρχείου + Read and write folder Ανάγνωση και εγγραφή φακέλου + Revoke Ανάκληση + Revoke removes the access kept for every version of the script. A folder's access covers everything in it. Η ανάκληση αφαιρεί την πρόσβαση που έχει αποθηκευτεί για κάθε έκδοση του σεναρίου. Η πρόσβαση σε φάκελο καλύπτει όλο το περιεχόμενό του. +@msg Script file access revoked Η πρόσβαση του σεναρίου σε αρχεία ανακλήθηκε +@msg The script file access was already revoked Η πρόσβαση του σεναρίου σε αρχεία είχε ήδη ανακληθεί Deny Άρνηση A script can change the open documents and can write files through the commands it runs. Run only scripts you trust. Ένα σενάριο μπορεί να αλλάξει τα ανοιχτά έγγραφα και να γράψει αρχεία μέσω των εντολών που εκτελεί. Εκτελείτε μόνο σενάρια που εμπιστεύεστε. Do not show this warning again Να μην εμφανιστεί ξανά αυτή η προειδοποίηση diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index 3f83e928e4..6c9867b07c 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -4894,6 +4894,14 @@ axis Both Ambos The script asks to read and write a folder you choose, with everything in it. El script pide leer y escribir una carpeta que usted elija, con todo su contenido. Allow Once Permitir una vez Always Allow This Script Permitir siempre este script + No script has kept file access. Ningún script tiene acceso a archivos guardado. + Read file Leer archivo + Read and write file Leer y escribir archivo + Read and write folder Leer y escribir carpeta + Revoke Revocar + Revoke removes the access kept for every version of the script. A folder's access covers everything in it. Revocar quita el acceso guardado para cada versión del script. El acceso a una carpeta abarca todo su contenido. +@msg Script file access revoked Acceso del script a archivos revocado +@msg The script file access was already revoked El acceso del script a archivos ya estaba revocado Deny Denegar A script can change the open documents and can write files through the commands it runs. Run only scripts you trust. Un script puede cambiar los documentos abiertos y escribir archivos mediante los comandos que ejecuta. Ejecute solo scripts de confianza. Do not show this warning again No volver a mostrar esta advertencia diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index a4d85b23e8..bba3adf2e7 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -5135,6 +5135,14 @@ imageTrace Outline Ääriviiva The script asks to read and write a folder you choose, with everything in it. Komentosarja pyytää lupaa lukea ja kirjoittaa valitsemasi kansion ja kaiken sen sisällön. Allow Once Salli kerran Always Allow This Script Salli tämä komentosarja aina + No script has kept file access. Millään komentosarjalla ei ole tallennettua tiedostojen käyttöoikeutta. + Read file Tiedoston luku + Read and write file Tiedoston luku ja kirjoitus + Read and write folder Kansion luku ja kirjoitus + Revoke Peruuta oikeus + Revoke removes the access kept for every version of the script. A folder's access covers everything in it. Peruuta oikeus poistaa käyttöoikeuden, joka on tallennettu komentosarjan jokaiselle versiolle. Kansion käyttöoikeus kattaa kaiken sen sisällön. +@msg Script file access revoked Komentosarjan tiedostojen käyttöoikeus peruttu +@msg The script file access was already revoked Komentosarjan tiedostojen käyttöoikeus oli jo peruttu Deny Estä A script can change the open documents and can write files through the commands it runs. Run only scripts you trust. Komentosarja voi muuttaa avoimia asiakirjoja ja kirjoittaa tiedostoja suorittamillaan komennoilla. Suorita vain komentosarjoja, joihin luotat. Do not show this warning again Älä näytä tätä varoitusta uudelleen diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 8f56486157..f31aad04d4 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -4876,6 +4876,14 @@ axis Both Les deux The script asks to read and write a folder you choose, with everything in it. Le script demande à lire et écrire un dossier que vous choisissez, avec tout son contenu. Allow Once Autoriser une fois Always Allow This Script Toujours autoriser ce script + No script has kept file access. Aucun script n’a conservé d’accès aux fichiers. + Read file Lire le fichier + Read and write file Lire et écrire le fichier + Read and write folder Lire et écrire le dossier + Revoke Révoquer + Revoke removes the access kept for every version of the script. A folder's access covers everything in it. Révoquer supprime l’accès conservé pour chaque version du script. L’accès à un dossier couvre tout son contenu. +@msg Script file access revoked Accès du script aux fichiers révoqué +@msg The script file access was already revoked L’accès du script aux fichiers était déjà révoqué Deny Refuser A script can change the open documents and can write files through the commands it runs. Run only scripts you trust. Un script peut modifier les documents ouverts et écrire des fichiers au moyen des commandes qu’il exécute. N’exécutez que des scripts de confiance. Do not show this warning again Ne plus afficher cet avertissement diff --git a/crates/ui-egui/src/i18n/gu.tsv b/crates/ui-egui/src/i18n/gu.tsv index 0bb7c9b71f..ea24ffdd4f 100644 --- a/crates/ui-egui/src/i18n/gu.tsv +++ b/crates/ui-egui/src/i18n/gu.tsv @@ -3979,6 +3979,15 @@ arrowhead Feather પીંછું Show East Asian Options પૂર્વ એશિયન વિકલ્પો બતાવો Show Edges કિનારીઓ બતાવો Show External Script Warning બાહ્ય સ્ક્રિપ્ટ ચેતવણી બતાવો + Script File Access સ્ક્રિપ્ટની ફાઇલ ઍક્સેસ + No script has kept file access. કોઈ સ્ક્રિપ્ટ પાસે સાચવેલ ફાઇલ ઍક્સેસ નથી. + Read file ફાઇલ વાંચો + Read and write file ફાઇલ વાંચો અને લખો + Read and write folder ફોલ્ડર વાંચો અને લખો + Revoke પરવાનગી પાછી ખેંચો + Revoke removes the access kept for every version of the script. A folder's access covers everything in it. પરવાનગી પાછી ખેંચવાથી સ્ક્રિપ્ટના દરેક સંસ્કરણ માટે સાચવેલ ઍક્સેસ દૂર થાય છે. ફોલ્ડરની ઍક્સેસમાં તેની અંદરનું બધું આવે છે. +@msg Script file access revoked સ્ક્રિપ્ટની ફાઇલ ઍક્સેસ પાછી ખેંચી +@msg The script file access was already revoked સ્ક્રિપ્ટની ફાઇલ ઍક્સેસ પહેલેથી પાછી ખેંચાઈ હતી Show Find Field શોધ ફીલ્ડ બતાવો Show Font Height Options ફોન્ટ ઊંચાઈ વિકલ્પો બતાવો Show Font Names in English ફોન્ટ નામો અંગ્રેજીમાં બતાવો diff --git a/crates/ui-egui/src/i18n/hi.tsv b/crates/ui-egui/src/i18n/hi.tsv index e9509d9202..9e8f4858ca 100644 --- a/crates/ui-egui/src/i18n/hi.tsv +++ b/crates/ui-egui/src/i18n/hi.tsv @@ -7568,6 +7568,14 @@ arrowhead Feather पंख The script asks to read and write a folder you choose, with everything in it. स्क्रिप्ट आपका चुना हुआ फ़ोल्डर और उसकी सारी सामग्री पढ़ने और लिखने की अनुमति माँगती है। Allow Once एक बार अनुमति दें Always Allow This Script इस स्क्रिप्ट को हमेशा अनुमति दें + No script has kept file access. किसी भी स्क्रिप्ट के पास रखी गई फ़ाइल पहुँच नहीं है। + Read file फ़ाइल पढ़ें + Read and write file फ़ाइल पढ़ें और लिखें + Read and write folder फ़ोल्डर पढ़ें और लिखें + Revoke वापस लें + Revoke removes the access kept for every version of the script. A folder's access covers everything in it. वापस लें स्क्रिप्ट के हर संस्करण के लिए रखी गई पहुँच हटा देता है। किसी फ़ोल्डर की पहुँच में उसके भीतर का सब कुछ शामिल है। +@msg Script file access revoked स्क्रिप्ट की फ़ाइल पहुँच वापस ली गई +@msg The script file access was already revoked स्क्रिप्ट की फ़ाइल पहुँच पहले ही वापस ली जा चुकी थी Deny अस्वीकार करें A script can change the open documents and can write files through the commands it runs. Run only scripts you trust. स्क्रिप्ट खुले दस्तावेज़ बदल सकती है और अपने चलाए कमांड से फ़ाइलें लिख सकती है। केवल भरोसेमंद स्क्रिप्ट चलाएँ। Do not show this warning again यह चेतावनी फिर न दिखाएँ diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index 87f050ef0d..3a99075b4c 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -5747,6 +5747,14 @@ imageTrace Outline Körvonal The script asks to read and write a folder you choose, with everything in it. A parancsfájl egy Ön által választott mappa és teljes tartalma olvasását és írását kéri. Allow Once Engedélyezés egyszer Always Allow This Script A parancsfájl engedélyezése mindig + No script has kept file access. Egy parancsfájlnak sincs megőrzött fájlhozzáférése. + Read file Fájl olvasása + Read and write file Fájl olvasása és írása + Read and write folder Mappa olvasása és írása + Revoke Engedély visszavonása + Revoke removes the access kept for every version of the script. A folder's access covers everything in it. Az Engedély visszavonása a parancsfájl minden verziójához megőrzött hozzáférést eltávolítja. Egy mappához való hozzáférés a teljes tartalmára kiterjed. +@msg Script file access revoked A parancsfájl fájlhozzáférése visszavonva +@msg The script file access was already revoked A parancsfájl fájlhozzáférése már vissza volt vonva Deny Elutasítás A script can change the open documents and can write files through the commands it runs. Run only scripts you trust. A parancsfájl módosíthatja a megnyitott dokumentumokat, és a futtatott parancsokkal fájlokat írhat. Csak megbízható parancsfájlokat futtasson. Do not show this warning again Ne jelenjen meg többé ez a figyelmeztetés diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index 924d3d80b5..853ee465b7 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -5526,6 +5526,14 @@ imageTrace Outline Kontur The script asks to read and write a folder you choose, with everything in it. Skrip meminta izin untuk membaca dan menulis folder yang Anda pilih, beserta seluruh isinya. Allow Once Izinkan Sekali Always Allow This Script Selalu Izinkan Skrip Ini + No script has kept file access. Tidak ada skrip yang memiliki akses berkas tersimpan. + Read file Baca Berkas + Read and write file Baca dan Tulis Berkas + Read and write folder Baca dan Tulis Folder + Revoke Cabut + Revoke removes the access kept for every version of the script. A folder's access covers everything in it. Cabut menghapus akses yang disimpan untuk setiap versi skrip. Akses ke folder mencakup semua isinya. +@msg Script file access revoked Akses berkas skrip dicabut +@msg The script file access was already revoked Akses berkas skrip sudah dicabut Deny Tolak A script can change the open documents and can write files through the commands it runs. Run only scripts you trust. Skrip dapat mengubah dokumen yang terbuka dan menulis file melalui perintah yang dijalankannya. Jalankan hanya skrip yang Anda percayai. Do not show this warning again Jangan tampilkan peringatan ini lagi diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index 5f47e3f117..5a290e168a 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -4953,6 +4953,14 @@ axis Both Entrambi The script asks to read and write a folder you choose, with everything in it. Lo script chiede di leggere e scrivere una cartella che scegli, con tutto il suo contenuto. Allow Once Consenti una volta Always Allow This Script Consenti sempre questo script + No script has kept file access. Nessuno script ha conservato un accesso ai file. + Read file Lettura file + Read and write file Lettura e scrittura file + Read and write folder Lettura e scrittura cartella + Revoke Revoca + Revoke removes the access kept for every version of the script. A folder's access covers everything in it. Revoca rimuove l'accesso conservato per ogni versione dello script. L'accesso a una cartella comprende tutto il suo contenuto. +@msg Script file access revoked Accesso dello script ai file revocato +@msg The script file access was already revoked L'accesso dello script ai file era già stato revocato Deny Nega A script can change the open documents and can write files through the commands it runs. Run only scripts you trust. Uno script può modificare i documenti aperti e scrivere file tramite i comandi che esegue. Esegui solo script di cui ti fidi. Do not show this warning again Non mostrare più questo avviso diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index 9a1b5f6354..6dc915f9aa 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -5779,6 +5779,14 @@ variable-list-end {0}, {1} {0}、{1} The script asks to read and write a folder you choose, with everything in it. スクリプトが、選択したフォルダーとその中身すべての読み書きを求めています。 Allow Once 今回のみ許可 Always Allow This Script このスクリプトを常に許可 + No script has kept file access. ファイルアクセスを保持しているスクリプトはありません。 + Read file ファイルの読み取り + Read and write file ファイルの読み取りと書き込み + Read and write folder フォルダーの読み取りと書き込み + Revoke 許可を取り消す + Revoke removes the access kept for every version of the script. A folder's access covers everything in it. 「許可を取り消す」は、スクリプトのすべてのバージョンに保持されたアクセスを削除します。フォルダーへのアクセスには、その中のすべてが含まれます。 +@msg Script file access revoked スクリプトのファイルアクセスを取り消しました +@msg The script file access was already revoked スクリプトのファイルアクセスはすでに取り消されています Deny 拒否 A script can change the open documents and can write files through the commands it runs. Run only scripts you trust. スクリプトは開いているドキュメントを変更でき、実行するコマンドを通じてファイルを書き込むこともできます。信頼できるスクリプトだけを実行してください。 Do not show this warning again 今後この警告を表示しない diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index 8eeacee621..6932462a4e 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -8448,6 +8448,14 @@ imageTrace Outline კონტური The script asks to read and write a folder you choose, with everything in it. სკრიპტი ითხოვს თქვენ მიერ არჩეული საქაღალდისა და მთელი მისი შიგთავსის წაკითხვასა და ჩაწერას. Allow Once ერთხელ დაშვება Always Allow This Script ამ სკრიპტის ყოველთვის დაშვება + No script has kept file access. არცერთ სკრიპტს არ აქვს შენახული წვდომა ფაილებზე. + Read file ფაილის წაკითხვა + Read and write file ფაილის წაკითხვა და ჩაწერა + Read and write folder საქაღალდის წაკითხვა და ჩაწერა + Revoke ნებართვის გაუქმება + Revoke removes the access kept for every version of the script. A folder's access covers everything in it. ნებართვის გაუქმება შლის სკრიპტის ყველა ვერსიისთვის შენახულ წვდომას. საქაღალდეზე წვდომა მოიცავს მასში არსებულ ყველაფერს. +@msg Script file access revoked სკრიპტის წვდომა ფაილებზე გაუქმდა +@msg The script file access was already revoked სკრიპტის წვდომა ფაილებზე უკვე გაუქმებული იყო Deny უარყოფა A script can change the open documents and can write files through the commands it runs. Run only scripts you trust. სკრიპტს შეუძლია ღია დოკუმენტების შეცვლა და მის მიერ გაშვებული ბრძანებებით ფაილების ჩაწერა. გაუშვით მხოლოდ სანდო სკრიპტები. Do not show this warning again აღარ აჩვენო ეს გაფრთხილება diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index 57e0b8be10..bddb440aee 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -5708,6 +5708,14 @@ variable-list-end {0}, {1} {0} 및 {1} The script asks to read and write a folder you choose, with everything in it. 스크립트가 선택한 폴더와 그 안의 모든 항목을 읽고 쓰도록 요청합니다. Allow Once 한 번 허용 Always Allow This Script 이 스크립트 항상 허용 + No script has kept file access. 파일 접근을 유지한 스크립트가 없습니다. + Read file 파일 읽기 + Read and write file 파일 읽기 및 쓰기 + Read and write folder 폴더 읽기 및 쓰기 + Revoke 권한 취소 + Revoke removes the access kept for every version of the script. A folder's access covers everything in it. 권한 취소는 스크립트의 모든 버전에 유지된 접근을 제거합니다. 폴더 접근에는 폴더 안의 모든 항목이 포함됩니다. +@msg Script file access revoked 스크립트 파일 접근 권한을 취소했습니다 +@msg The script file access was already revoked 스크립트 파일 접근 권한이 이미 취소되었습니다 Deny 거부 A script can change the open documents and can write files through the commands it runs. Run only scripts you trust. 스크립트는 열려 있는 문서를 변경하고 실행하는 명령을 통해 파일을 쓸 수 있습니다. 신뢰할 수 있는 스크립트만 실행하세요. Do not show this warning again 이 경고를 다시 표시하지 않음 diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index 5ed5cdc3e0..d00f9960df 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -5526,6 +5526,14 @@ imageTrace Outline Contour The script asks to read and write a folder you choose, with everything in it. Het script vraagt een map die u kiest te lezen en te schrijven, met alles wat erin staat. Allow Once Eenmaal toestaan Always Allow This Script Dit script altijd toestaan + No script has kept file access. Geen enkel script heeft bewaarde bestandstoegang. + Read file Bestand lezen + Read and write file Bestand lezen en schrijven + Read and write folder Map lezen en schrijven + Revoke Intrekken + Revoke removes the access kept for every version of the script. A folder's access covers everything in it. Intrekken verwijdert de toegang die voor elke versie van het script is bewaard. Toegang tot een map omvat alles erin. +@msg Script file access revoked Bestandstoegang van script ingetrokken +@msg The script file access was already revoked De bestandstoegang van het script was al ingetrokken Deny Weigeren A script can change the open documents and can write files through the commands it runs. Run only scripts you trust. Een script kan de geopende documenten wijzigen en via de uitgevoerde opdrachten bestanden schrijven. Voer alleen scripts uit die u vertrouwt. Do not show this warning again Deze waarschuwing niet meer tonen diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index 74029133dc..6b41f2febc 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -5058,6 +5058,14 @@ imageTrace Outline Kontur The script asks to read and write a folder you choose, with everything in it. Skrypt prosi o odczyt i zapis wybranego przez Ciebie folderu wraz z całą jego zawartością. Allow Once Zezwól raz Always Allow This Script Zawsze zezwalaj temu skryptowi + No script has kept file access. Żaden skrypt nie ma zachowanego dostępu do plików. + Read file Odczyt pliku + Read and write file Odczyt i zapis pliku + Read and write folder Odczyt i zapis folderu + Revoke Odwołaj + Revoke removes the access kept for every version of the script. A folder's access covers everything in it. Odwołaj usuwa dostęp zachowany dla każdej wersji skryptu. Dostęp do folderu obejmuje całą jego zawartość. +@msg Script file access revoked Odwołano dostęp skryptu do plików +@msg The script file access was already revoked Dostęp skryptu do plików został już odwołany Deny Odmów A script can change the open documents and can write files through the commands it runs. Run only scripts you trust. Skrypt może zmieniać otwarte dokumenty i zapisywać pliki za pomocą wykonywanych poleceń. Uruchamiaj tylko skrypty, którym ufasz. Do not show this warning again Nie pokazuj więcej tego ostrzeżenia diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index a1747af0b2..6cc30c65b5 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -6097,6 +6097,14 @@ variable-list-end {0}, {1} {0} e {1} The script asks to read and write a folder you choose, with everything in it. O script pede para ler e gravar uma pasta que você escolher, com todo o seu conteúdo. Allow Once Permitir uma vez Always Allow This Script Sempre permitir este script + No script has kept file access. Nenhum script manteve acesso a arquivos. + Read file Ler arquivo + Read and write file Ler e gravar arquivo + Read and write folder Ler e gravar pasta + Revoke Revogar + Revoke removes the access kept for every version of the script. A folder's access covers everything in it. Revogar remove o acesso mantido para cada versão do script. O acesso a uma pasta abrange tudo o que ela contém. +@msg Script file access revoked Acesso do script a arquivos revogado +@msg The script file access was already revoked O acesso do script a arquivos já estava revogado Deny Negar A script can change the open documents and can write files through the commands it runs. Run only scripts you trust. Um script pode alterar os documentos abertos e gravar arquivos pelos comandos que executa. Execute apenas scripts em que você confia. Do not show this warning again Não mostrar este aviso novamente diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index ca0c8d5145..59bc9f7d62 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -4929,6 +4929,14 @@ axis Both Оба The script asks to read and write a folder you choose, with everything in it. Скрипт запрашивает чтение и запись выбранной вами папки со всем её содержимым. Allow Once Разрешить один раз Always Allow This Script Всегда разрешать этот скрипт + No script has kept file access. Ни у одного скрипта нет сохранённого доступа к файлам. + Read file Чтение файла + Read and write file Чтение и запись файла + Read and write folder Чтение и запись папки + Revoke Отозвать + Revoke removes the access kept for every version of the script. A folder's access covers everything in it. «Отозвать» удаляет доступ, сохранённый для каждой версии скрипта. Доступ к папке распространяется на всё её содержимое. +@msg Script file access revoked Доступ скрипта к файлам отозван +@msg The script file access was already revoked Доступ скрипта к файлам уже был отозван Deny Запретить A script can change the open documents and can write files through the commands it runs. Run only scripts you trust. Скрипт может изменять открытые документы и записывать файлы с помощью выполняемых команд. Запускайте только те скрипты, которым доверяете. Do not show this warning again Больше не показывать это предупреждение diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index c26474cf93..d8355b2c4a 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -4791,6 +4791,14 @@ axis Both Båda The script asks to read and write a folder you choose, with everything in it. Skriptet ber om att läsa och skriva en mapp som du väljer, med allt innehåll. Allow Once Tillåt en gång Always Allow This Script Tillåt alltid det här skriptet + No script has kept file access. Inget skript har sparad filåtkomst. + Read file Läs fil + Read and write file Läs och skriv fil + Read and write folder Läs och skriv mapp + Revoke Återkalla + Revoke removes the access kept for every version of the script. A folder's access covers everything in it. Återkalla tar bort åtkomsten som sparats för varje version av skriptet. Åtkomst till en mapp omfattar allt i den. +@msg Script file access revoked Skriptets filåtkomst har återkallats +@msg The script file access was already revoked Skriptets filåtkomst var redan återkallad Deny Neka A script can change the open documents and can write files through the commands it runs. Run only scripts you trust. Ett skript kan ändra de öppna dokumenten och skriva filer genom de kommandon det kör. Kör bara skript du litar på. Do not show this warning again Visa inte den här varningen igen diff --git a/crates/ui-egui/src/i18n/tests.rs b/crates/ui-egui/src/i18n/tests.rs index 2ca2c76e03..a95d4cbf1b 100644 --- a/crates/ui-egui/src/i18n/tests.rs +++ b/crates/ui-egui/src/i18n/tests.rs @@ -3024,6 +3024,41 @@ fn script_file_messages_translate_in_every_complete_message_language() { assert_eq!(message(de, "Script file access denied: C:/x/a.txt"), "Dateizugriff des Skripts verweigert: C:/x/a.txt"); } +/// Preferences › General › Script File Access: its labels have a row in every catalog with menus, +/// and the status messages of its Revoke button a translated row in every complete-message +/// language. +#[test] +fn script_file_access_list_strings_are_in_complete_catalogs() { + let labels = [ + "Script File Access", + "No script has kept file access.", + "Read file", + "Read and write file", + "Read and write folder", + "Revoke", + "Revoke removes the access kept for every version of the script. A folder's access covers everything in it.", + ]; + let literals = tl_literals(); + let mut missing = vec![]; + for label in labels { + assert!(literals.contains(label), "{label:?} is no longer a tl! literal"); + for lang in LANGUAGES.iter().filter(|lang| lang.complete_menus) { + if lang.catalog().plain(label).is_none_or(|row| row == label) { + missing.push(format!("{} {label}", lang.code)); + } + } + } + assert!(missing.is_empty(), "{missing:?}"); + let messages = message_literals(); + for m in ["Script file access revoked", "The script file access was already revoked"] { + assert!(messages.contains(m), "{m:?} is no longer a message"); + for code in COMPLETE_MESSAGES { + let lang = Lang::from_code(code).expect("registered"); + assert_ne!(message(lang, m), m, "{code}: {m}"); + } + } +} + /// The error that `text.setFormat` and the paragraph style commands give when a justification /// setting's Minimum, Desired and Maximum are out of order is translated in every /// complete-message language, with the setting's name kept. diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index 82186ebcdd..cd74ca9166 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -4643,6 +4643,14 @@ axis Both Her İkisi The script asks to read and write a folder you choose, with everything in it. Betik, seçtiğiniz bir klasörü içindeki her şeyle birlikte okumak ve yazmak için izin istiyor. Allow Once Bir Kez İzin Ver Always Allow This Script Bu Betiğe Her Zaman İzin Ver + No script has kept file access. Hiçbir betiğin kayıtlı dosya erişimi yok. + Read file Dosya Okuma + Read and write file Dosya Okuma ve Yazma + Read and write folder Klasör Okuma ve Yazma + Revoke İzni Kaldır + Revoke removes the access kept for every version of the script. A folder's access covers everything in it. İzni Kaldır, betiğin her sürümü için kayıtlı erişimi kaldırır. Bir klasöre erişim, içindeki her şeyi kapsar. +@msg Script file access revoked Betiğin dosya erişimi kaldırıldı +@msg The script file access was already revoked Betiğin dosya erişimi zaten kaldırılmıştı Deny Reddet A script can change the open documents and can write files through the commands it runs. Run only scripts you trust. Bir betik açık belgeleri değiştirebilir ve çalıştırdığı komutlarla dosya yazabilir. Yalnızca güvendiğiniz betikleri çalıştırın. Do not show this warning again Bu uyarıyı bir daha gösterme diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index de3329ef10..eedb12c21a 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -4937,6 +4937,14 @@ axis Both Обидві The script asks to read and write a folder you choose, with everything in it. Скрипт просить дозволу читати й записувати вибрану вами папку з усім її вмістом. Allow Once Дозволити один раз Always Allow This Script Завжди дозволяти цей скрипт + No script has kept file access. Жоден скрипт не має збереженого доступу до файлів. + Read file Читання файлу + Read and write file Читання й запис файлу + Read and write folder Читання й запис папки + Revoke Відкликати + Revoke removes the access kept for every version of the script. A folder's access covers everything in it. «Відкликати» прибирає доступ, збережений для кожної версії скрипту. Доступ до папки охоплює весь її вміст. +@msg Script file access revoked Доступ скрипту до файлів відкликано +@msg The script file access was already revoked Доступ скрипту до файлів уже було відкликано Deny Заборонити A script can change the open documents and can write files through the commands it runs. Run only scripts you trust. Скрипт може змінювати відкриті документи й записувати файли за допомогою команд, які виконує. Запускайте лише ті скрипти, яким довіряєте. Do not show this warning again Більше не показувати це попередження diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index 675143a8d6..da6d0ae64d 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -5415,6 +5415,14 @@ theme Appearance Giao diện The script asks to read and write a folder you choose, with everything in it. Tập lệnh yêu cầu đọc và ghi một thư mục bạn chọn, cùng mọi thứ bên trong. Allow Once Cho phép một lần Always Allow This Script Luôn cho phép tập lệnh này + No script has kept file access. Không có tập lệnh nào được giữ quyền truy cập tệp. + Read file Đọc tệp + Read and write file Đọc và ghi tệp + Read and write folder Đọc và ghi thư mục + Revoke Thu hồi + Revoke removes the access kept for every version of the script. A folder's access covers everything in it. Thu hồi gỡ quyền truy cập đã giữ cho mọi phiên bản của tập lệnh. Quyền truy cập một thư mục bao gồm mọi thứ bên trong. +@msg Script file access revoked Đã thu hồi quyền truy cập tệp của tập lệnh +@msg The script file access was already revoked Quyền truy cập tệp của tập lệnh đã được thu hồi trước đó Deny Từ chối A script can change the open documents and can write files through the commands it runs. Run only scripts you trust. Tập lệnh có thể thay đổi các tài liệu đang mở và ghi tệp thông qua các lệnh mà nó chạy. Chỉ chạy những tập lệnh bạn tin cậy. Do not show this warning again Không hiện lại cảnh báo này diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index 57f6a4403b..5f66731afe 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -5444,6 +5444,14 @@ imageTrace Outline 轮廓 The script asks to read and write a folder you choose, with everything in it. 脚本请求读写您选择的文件夹及其中的所有内容。 Allow Once 允许一次 Always Allow This Script 始终允许此脚本 + No script has kept file access. 没有脚本保留了文件访问权限。 + Read file 读取文件 + Read and write file 读取和写入文件 + Read and write folder 读取和写入文件夹 + Revoke 收回权限 + Revoke removes the access kept for every version of the script. A folder's access covers everything in it. “收回权限”会移除为脚本每个版本保留的访问权限。文件夹的访问权限包括其中的所有内容。 +@msg Script file access revoked 已收回脚本的文件访问权限 +@msg The script file access was already revoked 脚本的文件访问权限已被收回 Deny 拒绝 A script can change the open documents and can write files through the commands it runs. Run only scripts you trust. 脚本可以更改打开的文档,并可通过其运行的命令写入文件。请只运行您信任的脚本。 Do not show this warning again 不再显示此警告 diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index 9834c17ea6..d430105f73 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -2790,6 +2790,14 @@ file-filter Templates 範本 The script asks to read and write a folder you choose, with everything in it. 指令碼要求讀寫您選擇的資料夾及其中的所有內容。 Allow Once 允許一次 Always Allow This Script 一律允許此指令碼 + No script has kept file access. 沒有指令碼保留檔案存取權。 + Read file 讀取檔案 + Read and write file 讀取和寫入檔案 + Read and write folder 讀取和寫入資料夾 + Revoke 收回權限 + Revoke removes the access kept for every version of the script. A folder's access covers everything in it. 「收回權限」會移除為指令碼每個版本保留的存取權。資料夾的存取權包含其中的所有內容。 +@msg Script file access revoked 已收回指令碼的檔案存取權 +@msg The script file access was already revoked 指令碼的檔案存取權已被收回 Deny 拒絕 A script can change the open documents and can write files through the commands it runs. Run only scripts you trust. 指令碼可以變更開啟的文件,並可透過其執行的命令寫入檔案。請只執行您信任的指令碼。 Do not show this warning again 不再顯示此警告 diff --git a/crates/ui-egui/src/prefs_dialog.rs b/crates/ui-egui/src/prefs_dialog.rs index f6bd364449..19aa7d9e66 100644 --- a/crates/ui-egui/src/prefs_dialog.rs +++ b/crates/ui-egui/src/prefs_dialog.rs @@ -13,6 +13,7 @@ use crate::theme::{self, Accent, Brightness, Scheme, Tokens}; use crate::{VectorcraftApp, widgets}; mod descriptions; +mod script_access; /// UI-only fields shown in the dialog (backed by `UiState`, not engine prefs). pub const UI_FIELDS: &[(&str, &str, &str)] = &[ @@ -55,6 +56,8 @@ pub fn open(app: &mut VectorcraftApp, category: Option<&str>) { fields.insert("__desktopKeepsFrame".into(), json!(app.desktop_keeps_frame)); fields.insert("__search".into(), json!("")); fields.insert("__focusSearch".into(), json!(true)); + // Read-only: the script file access kept with Always (General › Script File Access). + script_access::load(app, &mut fields); app.ui.dialog = Some(Dialog { kind: "preferences".into(), fields }); } @@ -780,6 +783,9 @@ fn category_fields(ui: &mut egui::Ui, app: &mut VectorcraftApp, d: &mut Dialog, } found_paint(ui, d, mark); described.row(ui, sp.key, top); + if sp.key == "showExternalScriptWarning" { + script_access::show(ui, app, d); + } } described } diff --git a/crates/ui-egui/src/prefs_dialog/script_access.rs b/crates/ui-egui/src/prefs_dialog/script_access.rs new file mode 100644 index 0000000000..abbe87386d --- /dev/null +++ b/crates/ui-egui/src/prefs_dialog/script_access.rs @@ -0,0 +1,202 @@ +//! Preferences › General › Script File Access: the file access people allowed scripts with Always +//! Allow This Script in a script's file dialog (`script.grants`), one row for each script and path, +//! each with a Revoke button (`script.grants.revoke`). + +use std::collections::BTreeMap; + +use serde_json::{Map, Value, json}; +use vectorcraft_plugins::permissions; + +use crate::state::Dialog; +use crate::theme::{self, Tokens}; +use crate::{VectorcraftApp, widgets}; + +/// The dialog field that holds the rows, `[{script, path, access, versions}]`. It is absent where +/// the session keeps no grants (no settings folder, and the web), and the section is not shown. +pub(super) const ROWS: &str = "__scriptAccess"; + +/// The dialog field that holds the row whose Revoke button takes the keyboard focus next. +const FOCUS: &str = "__scriptAccessFocus"; + +/// The most characters of a path a row shows. +const MAX_SHOWN_PATH: usize = 1024; + +/// A row's height in the list. +const ROW_HEIGHT: f32 = 30.0; + +/// The list's height before it scrolls. +const LIST_HEIGHT: f32 = 180.0; + +/// The kept grants (`script.grants`) as the rows of the field [`ROWS`] in the Preferences dialog's +/// `fields`. Where the session keeps no grants, the field is removed. +pub(super) fn load(app: &mut VectorcraftApp, fields: &mut Map) { + match app.session.execute("script.grants", &json!({})) { + Ok(v) if !v["file"].is_null() => { + fields.insert(ROWS.into(), Value::Array(rows(&v["grants"]))); + } + _ => { + fields.remove(ROWS); + } + } +} + +/// The rows for the grants `grants` lists: one for each script and path, sorted by script and then +/// by path, with the widest access any kept version of the pair has (`folder`, then `write`, then +/// `read`) and how many versions are kept. A grant without a script or a path is left out. +pub(super) fn rows(grants: &Value) -> Vec { + let rank = |access: &str| match access { + "folder" => 2, + "write" => 1, + _ => 0, + }; + let mut pairs: BTreeMap<(&str, &str), (&str, usize)> = BTreeMap::new(); + for g in grants.as_array().into_iter().flatten() { + let (Some(script), Some(path)) = (g["script"].as_str(), g["path"].as_str()) else { continue }; + let access = if g["folder"] == true { + "folder" + } else if g["write"] == true { + "write" + } else { + "read" + }; + let pair = pairs.entry((script, path)).or_insert((access, 0)); + if rank(access) > rank(pair.0) { + pair.0 = access; + } + pair.1 += 1; + } + pairs + .into_iter() + .map(|((script, path), (access, versions))| json!({"script": script, "path": path, "access": access, "versions": versions})) + .collect() +} + +/// `path` as a row shows it: control and bidirectional formatting characters written as escapes, +/// and at most [`MAX_SHOWN_PATH`] characters. +pub(super) fn shown(path: &str) -> String { + permissions::display_text(path, MAX_SHOWN_PATH) +} + +/// The label of a row's access. +fn access_label(access: &str) -> &'static str { + match access { + "folder" => tl!("Read and write folder"), + "write" => tl!("Read and write file"), + _ => tl!("Read file"), + } +} + +/// A line of the list: the script that the rows below it belong to, or a row, by its index. +enum Line { + Script(usize), + Row(usize), +} + +/// The section, after General › Show External Script Warning, when the dialog `d` has rows: each +/// script, its paths with their access and a Revoke button, or a line saying there are none. +pub(super) fn show(ui: &mut egui::Ui, app: &mut VectorcraftApp, d: &mut Dialog) { + let Some(rows) = d.fields.get(ROWS).and_then(Value::as_array).cloned() else { return }; + let t = Tokens::get(ui.ctx()); + ui.add_space(8.0); + ui.label(egui::RichText::new(tl!("Script File Access")).font(theme::semibold(12.5)).color(t.text_strong)); + ui.add_space(2.0); + if rows.is_empty() { + ui.label(egui::RichText::new(tl!("No script has kept file access.")).color(t.text_dim).size(11.5)); + return; + } + let mut lines = Vec::with_capacity(rows.len() * 2); + for (i, row) in rows.iter().enumerate() { + if i == 0 || rows[i - 1]["script"] != row["script"] { + lines.push(Line::Script(i)); + } + lines.push(Line::Row(i)); + } + let focus = d.fields.get(FOCUS).and_then(Value::as_u64).and_then(|i| usize::try_from(i).ok()); + let mut revoke_at = None; + // The widths of the access column and of the Revoke button, so the path takes the rest. + let text_width = |text: &str, font: egui::FontId| ui.painter().layout_no_wrap(text.to_string(), font, t.text).size().x; + let access_width = + ["folder", "write", "read"].map(|a| text_width(access_label(a), egui::FontId::proportional(11.5))).into_iter().fold(0.0, f32::max); + let revoke_width = (text_width(tl!("Revoke"), theme::semibold(12.5)) + 32.0).max(72.0); + // The list is as tall as its lines, up to LIST_HEIGHT, also at the bottom of the scrolled field + // list, where a scroll area would otherwise take only the height left in view. + let spacing = ui.spacing().item_spacing; + let height = ((ROW_HEIGHT + spacing.y) * lines.len() as f32 - spacing.y).min(LIST_HEIGHT); + let scroll = + egui::ScrollArea::vertical().id_salt("prefs-script-access").max_height(LIST_HEIGHT).min_scrolled_height(height).auto_shrink([false, true]); + scroll.show_rows(ui, ROW_HEIGHT, lines.len(), |ui, range| { + for line in &lines[range] { + let size = egui::vec2(ui.available_width(), ROW_HEIGHT); + match *line { + Line::Script(i) => { + let script = shown(rows[i]["script"].as_str().unwrap_or_default()); + ui.allocate_ui_with_layout(size, egui::Layout::left_to_right(egui::Align::Center), |ui| { + let text = egui::RichText::new(&script).color(t.text_strong).size(12.0); + ui.add(egui::Label::new(text).truncate()).on_hover_text(&script); + }); + } + Line::Row(i) => { + let row = &rows[i]; + let (script, path) = (shown(row["script"].as_str().unwrap_or_default()), shown(row["path"].as_str().unwrap_or_default())); + ui.allocate_ui_with_layout(size, egui::Layout::left_to_right(egui::Align::Center), |ui| { + ui.add_space(12.0); + // The path, then the access and the Revoke button at the right. + let gaps = 12.0 + 2.0 * ui.spacing().item_spacing.x; + let path_width = (ui.available_width() - access_width - revoke_width - gaps).max(40.0); + let cell = |width: f32| egui::vec2(width, ROW_HEIGHT); + ui.allocate_ui_with_layout(cell(path_width), egui::Layout::left_to_right(egui::Align::Center), |ui| { + ui.set_width(path_width); + ui.add(egui::Label::new(egui::RichText::new(&path).color(t.text)).truncate()).on_hover_text(&path); + }); + ui.add_space(12.0); + ui.allocate_ui_with_layout(cell(access_width), egui::Layout::left_to_right(egui::Align::Center), |ui| { + ui.set_width(access_width); + let access = egui::RichText::new(access_label(row["access"].as_str().unwrap_or_default())).color(t.text_dim).size(11.5); + ui.add(egui::Label::new(access).wrap_mode(egui::TextWrapMode::Extend)); + }); + let button = widgets::secondary_button(ui, tl!("Revoke")); + // A screen reader names the script and the path along with the button. + ui.ctx().accesskit_node_builder(button.id, |node| node.set_description(format!("{script}: {path}"))); + if focus == Some(i) { + button.request_focus(); + } + if button.on_hover_text(&path).clicked() { + revoke_at = Some(i); + } + }); + } + } + } + }); + if focus.is_some() { + d.fields.remove(FOCUS); + } + let note = tl!("Revoke removes the access kept for every version of the script. A folder's access covers everything in it."); + ui.label(egui::RichText::new(note).color(t.text_dim).size(11.0)); + if let Some(i) = revoke_at { + revoke(app, d, i); + } +} + +/// Revoke on the row `i` of the Preferences dialog `d`: every kept grant of its script and path is +/// removed (`script.grants.revoke`), the rows are read again and the row now at `i`, or the last +/// row, takes the keyboard focus. The status bar says what happened; on an error the rows stay as +/// they were. +pub(super) fn revoke(app: &mut VectorcraftApp, d: &mut Dialog, i: usize) { + let Some(row) = d.fields.get(ROWS).and_then(|rows| rows.get(i)).cloned() else { return }; + match app.run("script.grants.revoke", json!({"script": row["script"], "path": row["path"]})) { + Ok(v) => { + load(app, &mut d.fields); + let left = d.fields.get(ROWS).and_then(Value::as_array).map_or(0, Vec::len); + if left > 0 { + d.fields.insert(FOCUS.into(), json!(i.min(left - 1))); + } + if v["removed"].as_u64().unwrap_or(0) > 0 { + app.status("Script file access revoked"); + } else { + app.status("The script file access was already revoked"); + } + } + Err(e) => app.status(e), + } +} diff --git a/crates/ui-egui/src/prefs_dialog/tests.rs b/crates/ui-egui/src/prefs_dialog/tests.rs index c79ca22470..f201c553dc 100644 --- a/crates/ui-egui/src/prefs_dialog/tests.rs +++ b/crates/ui-egui/src/prefs_dialog/tests.rs @@ -3001,3 +3001,177 @@ fn every_description_names_a_setting_and_fits_in_every_language() { out.textures_delta.clear(); assert!(bad.is_empty(), "{}", bad.join("\n")); } + +/// A kept script file grant, as the grants file holds it. +fn grant(script: &std::path::Path, path: &std::path::Path, sha256: &str, write: bool, folder: bool) -> Value { + json!({"script": script.to_string_lossy(), "sha256": sha256, "code": [], "path": path.to_string_lossy(), "write": write, "folder": folder}) +} + +/// An app whose session keeps its script data in a new folder for test `name`, with a grants file +/// beside it that holds `grants`. → The app and the grants file. +fn app_with_grants(name: &str, grants: Value) -> (VectorcraftApp, std::path::PathBuf) { + let base = temp_folder(name); + let store = base.join(vectorcraft_engine::script::files::GRANTS_FILE); + std::fs::write(&store, serde_json::to_vec_pretty(&json!({"version": 1, "grants": grants})).unwrap()).unwrap(); + let mut a = app(); + a.session.attach_script_data(base.join("Script Data")); + (a, store) +} + +/// The rows General › Script File Access shows, as (script, path, access, versions). +fn access_rows(a: &VectorcraftApp) -> Vec<(String, String, String, u64)> { + let d = a.ui.dialog.as_ref().unwrap(); + let rows = d.fields.get(script_access::ROWS).and_then(Value::as_array).cloned().unwrap_or_default(); + rows.iter() + .map(|r| { + let s = |k: &str| r[k].as_str().unwrap_or_default().to_string(); + (s("script"), s("path"), s("access"), r["versions"].as_u64().unwrap_or(0)) + }) + .collect() +} + +/// The open Preferences dialog drawn in `ctx` with the field list scrolled by the wheel, over the +/// Keyboard Increment row, until the last text `label` lies wholly inside it → the texts of the +/// last frame that lie in their clip rectangle. +fn script_access_in_view(a: &mut VectorcraftApp, ctx: &egui::Context, label: &str) -> Vec<(String, egui::Rect)> { + description_frame(a, ctx, vec![]); + let texts = whole_texts_frame(a, ctx, vec![]); + let at = texts.iter().find(|(t, _)| t == "Keyboard Increment:").map(|(_, r)| r.center()).expect("General shows Keyboard Increment"); + let texts = description_frame(a, ctx, vec![egui::Event::PointerMoved(at)]).0; + scroll_into_view(a, ctx, texts, label) +} + +/// Click the first text `label` of `texts`, which the last frame in `ctx` drew, with the pointer. +fn click_shown(a: &mut VectorcraftApp, ctx: &egui::Context, texts: &[(String, egui::Rect)], label: &str) { + let at = texts.iter().find(|(t, _)| t == label).map(|(_, r)| r.center()).unwrap_or_else(|| panic!("no `{label}` in {texts:?}")); + let press = |pressed| egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() }; + description_frame(a, ctx, vec![egui::Event::PointerMoved(at)]); + description_frame(a, ctx, vec![press(true)]); + description_frame(a, ctx, vec![press(false)]); +} + +/// A new context with the app's fonts. +fn fonts_context() -> egui::Context { + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + ctx +} + +/// General › Script File Access lists each script and path once, with the widest access any kept +/// version of the pair has, and Revoke removes every kept version of that pair through +/// `script.grants.revoke`, so the next run asks again; the other pairs stay. +#[test] +fn script_file_access_lists_each_script_and_path_once_and_revoke_removes_them() { + let dir = std::env::temp_dir().join("vc-ui-prefs-grants-nowhere"); + let (a_js, b_js) = (dir.join("a.jsx"), dir.join("b.jsx")); + let (out, folder) = (dir.join("out.txt"), dir.join("work")); + let grants = json!([ + grant(&a_js, &out, "1", false, false), + grant(&a_js, &out, "2", true, false), + grant(&a_js, &folder, "1", true, true), + grant(&b_js, &out, "3", false, false), + ]); + let (mut a, store) = app_with_grants("grants-list", grants); + open(&mut a, Some("General")); + let (a_s, b_s, out_s, folder_s) = (a_js.to_string_lossy(), b_js.to_string_lossy(), out.to_string_lossy(), folder.to_string_lossy()); + let row = |s: &str, p: &str, access: &str, n: u64| (s.to_string(), p.to_string(), access.to_string(), n); + assert_eq!( + access_rows(&a), + [row(&a_s, &out_s, "write", 2), row(&a_s, &folder_s, "folder", 1), row(&b_s, &out_s, "read", 1)], + "one row for each script and path, sorted by script and then path" + ); + let ctx = fonts_context(); + let note = "Revoke removes the access kept for every version of the script. A folder's access covers everything in it."; + let texts = script_access_in_view(&mut a, &ctx, note); + let painted = |label: &str| texts.iter().filter(|(t, _)| t == label).count(); + for label in ["Script File Access", "Read and write file", "Read and write folder", "Read file"] { + assert_eq!(painted(label), 1, "{label:?} in {texts:?}"); + } + assert_eq!(painted("Revoke"), 3, "a Revoke for each row: {texts:?}"); + assert_eq!(painted(&a_s), 1, "the script shows once over its rows: {texts:?}"); + assert_eq!(painted(&out_s), 2, "{texts:?}"); + let rect = |label: &str| texts.iter().find(|(t, _)| t == label).map(|(_, r)| *r).unwrap_or_else(|| panic!("no `{label}`")); + let (path, access, revoke) = (rect(&out_s), rect("Read and write file"), rect("Revoke")); + assert!(path.max.x < access.min.x && access.max.x < revoke.min.x, "a row's path, access and Revoke do not overlap: {texts:?}"); + // The first Revoke is the first row's: a.jsx and out.txt, kept for two versions. + click_shown(&mut a, &ctx, &texts, "Revoke"); + assert_eq!(a.ui.status, "Script file access revoked"); + assert_eq!(access_rows(&a), [row(&a_s, &folder_s, "folder", 1), row(&b_s, &out_s, "read", 1)]); + let kept = a.session.execute("script.grants", &json!({})).unwrap(); + assert_eq!(kept["grants"].as_array().unwrap().len(), 2, "{kept}"); + let stored: Value = serde_json::from_slice(&std::fs::read(&store).unwrap()).unwrap(); + assert!(stored["grants"].as_array().unwrap().iter().all(|g| !(g["script"] == *a_s && g["path"] == *out_s)), "{stored}"); + let _ = std::fs::remove_dir_all(store.parent().unwrap()); +} + +/// Revoke on a row whose grants were removed elsewhere removes nothing and says so; with no kept +/// grants the section says there are none, and a session without a settings folder (the web among +/// them) shows no section. +#[test] +fn script_file_access_shows_none_and_a_revoke_of_a_removed_row() { + let dir = std::env::temp_dir().join("vc-ui-prefs-grants-nowhere"); + let (mut a, store) = app_with_grants("grants-gone", json!([grant(&dir.join("a.jsx"), &dir.join("out.txt"), "1", false, false)])); + open(&mut a, Some("General")); + assert_eq!(access_rows(&a).len(), 1); + a.session.execute("script.grants.revoke", &json!({"all": true})).unwrap(); + let mut d = a.ui.dialog.clone().unwrap(); + script_access::revoke(&mut a, &mut d, 0); + a.ui.dialog = Some(d); + assert_eq!(a.ui.status, "The script file access was already revoked"); + assert!(access_rows(&a).is_empty()); + let texts = script_access_in_view(&mut a, &fonts_context(), "No script has kept file access."); + assert!(texts.iter().any(|(t, _)| t == "Script File Access"), "{texts:?}"); + let _ = std::fs::remove_dir_all(store.parent().unwrap()); + let mut web = app(); + open(&mut web, Some("General")); + assert!(web.ui.dialog.as_ref().unwrap().fields.get(script_access::ROWS).is_none()); + let text = crate::tests_labels::painted_text(&mut web, |a, ui| show(a, ui.ctx())); + assert!(!text.contains("No script has kept file access."), "{text}"); +} + +/// A grants file that is not well formed or is larger than may be read is refused: Revoke shows +/// the error, grants nothing and leaves the file and the rows as they were. +#[test] +fn script_file_access_revoke_refuses_a_malformed_or_oversized_grants_file() { + let dir = std::env::temp_dir().join("vc-ui-prefs-grants-nowhere"); + let mut oversized = br#"{"version": 1, "grants": []}"#.to_vec(); + oversized.resize((4 << 20) + 1, b' '); + for (name, held) in + [("malformed", br#"{"version": 1, "grants": [{"script": "x"}]}"#.to_vec()), ("broken", b"{ not json".to_vec()), ("oversized", oversized)] + { + let (mut a, store) = app_with_grants(&format!("grants-{name}"), json!([grant(&dir.join("a.jsx"), &dir.join("out.txt"), "1", false, false)])); + open(&mut a, Some("General")); + let before = access_rows(&a); + assert_eq!(before.len(), 1, "{name}"); + std::fs::write(&store, &held).unwrap(); + let mut d = a.ui.dialog.clone().unwrap(); + script_access::revoke(&mut a, &mut d, 0); + a.ui.dialog = Some(d); + assert!(a.ui.status.contains("could not be saved"), "{name}: {}", a.ui.status); + assert_eq!(std::fs::read(&store).unwrap(), held, "{name}: the grants file is left as it was"); + assert_eq!(access_rows(&a), before, "{name}: the rows stay"); + let listed = a.session.execute("script.grants", &json!({})); + assert!( + listed.as_ref().is_ok_and(|v| v["grants"].as_array().is_some_and(Vec::is_empty)) || listed.is_err(), + "{name}: nothing is granted: {listed:?}" + ); + let _ = std::fs::remove_dir_all(store.parent().unwrap()); + } +} + +/// A script or path with control or bidirectional formatting characters shows them as escapes, so +/// it cannot break its row or draw as another name. +#[test] +fn script_file_access_shows_paths_as_plain_text() { + let dir = std::env::temp_dir().join("vc-ui-prefs-grants-nowhere"); + let (script, path) = (dir.join("a\u{202E}txt.jsx"), dir.join("two\nlines.txt")); + let (mut a, store) = app_with_grants("grants-plain", json!([grant(&script, &path, "1", false, false)])); + open(&mut a, Some("General")); + let (script_s, path_s) = (script_access::shown(&script.to_string_lossy()), script_access::shown(&path.to_string_lossy())); + assert!(script_s.ends_with("a\\u{202E}txt.jsx") && path_s.ends_with("two\\u{000A}lines.txt"), "{script_s} {path_s}"); + let texts = script_access_in_view(&mut a, &fonts_context(), &path_s); + assert!(texts.iter().any(|(t, _)| *t == script_s), "{texts:?}"); + let text: String = crate::tests_labels::painted_text(&mut a, |a, ui| show(a, ui.ctx())); + assert!(!text.contains('\u{202E}') && !text.contains("two\nlines"), "{text}"); + let _ = std::fs::remove_dir_all(store.parent().unwrap()); +} diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 5e8483f80a..8f60699871 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1040,6 +1040,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - Scripts: `$.line` is the line of the running script, counting from 1, and `$.stack` is the current stack trace ([the help page](https://extendscript.docsforadobe.dev/extendscript-tools-features/dollar-object/)). VectorCraft's own rules: both count lines in the file the code is in (the script, a file it included, a file `$.evalFile` ran, or the file of an earlier run of the named engine), and `$.stack` writes each frame as `name@file:line`, outermost first; code that `eval` or `Function` compiled keeps its own line in `[eval]`, and code whose place the engine no longer keeps is at line 0 of `[unknown]`. `crates/engine/src/tests/script_include.rs`, `crates/engine/src/tests/script_engines.rs`, `crates/js/src/extension_tests.rs`. - Scripts: `File` and `Folder` ([File object](https://extendscript.docsforadobe.dev/file-system-access/file-object/), [Folder object](https://extendscript.docsforadobe.dev/file-system-access/folder-object/)) name files and folders by platform or URI path, with `name`, `fsName`, `absoluteURI`, `relativeURI`, `parent`, `Folder.current` and `encode`/`decode`, and read them: `exists`, `length`, the dates, `getFiles` with a mask or a function, and `open('r')` with `read`, `readln`, `readch`, `seek`, `tell` and `close`, decoding by byte order mark, `encoding`, UTF-8 or CP1252. VectorCraft's own rules: a script reads only in its own folder and below (and inside the automation read roots when they are set); any other path and a network or device path are refused before anything is looked up, and a link that leads out is refused as well (`false` or `null`, with `error` set); a file is read whole up to 8 MiB and a run reads up to 32 MiB; `execute` is not available. `crates/engine/src/tests/script_io.rs`. - Scripts: `File` and `Folder` write ([File object](https://extendscript.docsforadobe.dev/file-system-access/file-object/), [Folder object](https://extendscript.docsforadobe.dev/file-system-access/folder-object/)): `open('w')`, `open('e')` and `open('a')` with `write` and `writeln` by `lineFeed`, `copy`, `remove` (a folder only when empty), `rename`, `folder.create()`, the `length` and `readonly` setters, and `File.openDialog`, `File.saveDialog`, `Folder.selectDialog`, `openDlg`, `saveDlg` and `selectDlg`, with a `filter` of file types or a filter function and `multiSelect`. VectorCraft's own rules: a script writes only in `Folder.temp` (one for the run, deleted when it ends), its own `Folder.userData` next to the settings, and what a person allowed it in a file dialog, once or always; Always keeps the grant for that script file with that text by its SHA-256 and for the sources the run evaluated (`$.evalFile`, `eval`, `Function`), so a run that evaluates other code, or whose named engine holds other code, loses it first; `script.grants` lists the grants and `script.grants.revoke` removes them; the settings folder is kept out of every grant; the commands a script runs with `vc.run` read and write only in the same places and the open documents' own files; a run with nobody to ask gets `null` from the dialogs; a file is written at close or when the run ends, 8 MiB a file and 32 MiB a run, and named in `written`, also after a run that failed. `crates/engine/src/tests/script_io.rs`. + - Scripts: Preferences › General › Script File Access lists the file access kept with Always Allow This Script (`script.grants`), one row for each script and path with its widest access (read file, read and write file, or read and write folder), and its Revoke button removes every kept version of that script and path (`script.grants.revoke`), so the next run asks again. Paths show control and bidirectional characters as escapes; a grants file that is not well formed or is over 4 MiB makes Revoke show its error and leaves the file as it was. VectorCraft's own addition. `crates/ui-egui/src/prefs_dialog/tests.rs` (`script_file_access_*`). - Scripts: `#strict on` (and `//@strict on`) runs the script with the checks the [`$` object](https://extendscript.docsforadobe.dev/extendscript-tools-features/dollar-object/) help page gives for `$.strict`: an assignment to a read-only property throws a `TypeError`, and so does a new property on an object that takes none. VectorCraft's own rules: a getter-only property counts as read-only, the objects that take no new properties are the non-extensible ones (`Object.preventExtensions`, `seal`, `freeze`, and the frozen `vc` and `$` objects), the last `#strict` line of the script and its includes sets the whole run, a file `$.evalFile` runs keeps its own line's checks for its code, and the rest of ES5 strict mode stays with `'use strict'`. Without the line, runs are unchanged. `crates/engine/src/tests/script_include.rs` (`strict_on_*`, `strict_mode_in_eval_file_is_scoped`), `crates/js/src/interp_tests.rs` (`strict_writes_are_separate_from_es5_strict`). - Scripts folder: File › Scripts lists the `.js` and `.jsx` files of the `Scripts` folder next to the preferences, each named after its file without the extension, with each subfolder as a submenu, above Check Script… and Other Script… (https://helpx.adobe.com/illustrator/desktop/automate-visualize-data/automate-actions/install-and-run-scripts.html). VectorCraft's own rules: the folder is read again when the window becomes active and when the File menu opens (in the macOS menu bar, when any of its menus opens, and the new listing shows the next time the menu opens), links are not followed, and one read stops at 2,048 entries, 512 scripts, 128 subfolders, 4 levels or 250 ms. `script.listInstalled` returns the listing. `crates/engine/src/tests/script_folder.rs`, `crates/ui-egui/src/tests/scripts_menu.rs`. - Messages over the window: `app.toast {message, level?, seconds?}` shows a message at the window's bottom right that does not stop work and closes after its time (4 seconds by default) or when clicked; at most 5 show at once, the newest lowest. Scripts raise one through `vc.run`, MCP clients through the command, and an action records it as a step. The limits are VectorCraft's own values. Tests: `cmd::toast::tests` in `vectorcraft-engine`, `toasts::tests` in `vectorcraft-ui-egui`. From 7b9603bb874c059b0377e3542a2409fee9c4e242 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 20 Nov 2026 23:50:12 -0800 Subject: [PATCH 023/151] Tests: the Slices keyboard test checks Line Color and starts from the search field keyboard_focus_on_a_slices_row_shows_its_description stopped at Show Slice Numbers, so nothing checked that keyboard focus on Line Color shows its sentence, and the test passed even when the first Tab did not start from the search field. It now uses tab_to_each, as the Hyphenation test does: it asserts the search field has the keyboard first, then tabs to Show Slice Numbers and Line Color in that order and checks that each focused control carries its sentence. --- crates/ui-egui/src/prefs_dialog/tests.rs | 18 +++++++----------- 1 file changed, 7 insertions(+), 11 deletions(-) diff --git a/crates/ui-egui/src/prefs_dialog/tests.rs b/crates/ui-egui/src/prefs_dialog/tests.rs index c79ca22470..bfce328bf7 100644 --- a/crates/ui-egui/src/prefs_dialog/tests.rs +++ b/crates/ui-egui/src/prefs_dialog/tests.rs @@ -2439,8 +2439,9 @@ fn hovering_a_slices_row_shows_its_description() { assert!(painted(&after, color) && !painted(&after, numbers), "the Line Color row's sentence shows: {after:?}"); } -/// Tab from the search field reaches Slices' first control, the Show Slice Numbers box: the line -/// shows its sentence and a screen reader gets it as the control's description. +/// Tab from the search field reaches Slices' Show Slice Numbers box and then its Line Color control, +/// in that order: the line shows each one's sentence in turn, and a screen reader gets it as the +/// focused control's description. #[test] fn keyboard_focus_on_a_slices_row_shows_its_description() { let mut a = app(); @@ -2451,16 +2452,11 @@ fn keyboard_focus_on_a_slices_row_shows_its_description() { description_frame(&mut a, &ctx, vec![]); description_frame(&mut a, &ctx, vec![]); let numbers = descriptions::description("showSliceNumbers").expect("Show Slice Numbers has a sentence"); - let mut shown = None; - for _ in 0..40 { - let (texts, described) = description_frame(&mut a, &ctx, key_press(egui::Key::Tab, egui::Modifiers::NONE)); - if painted(&texts, numbers) { - shown = Some(described); - break; - } + let color = descriptions::description("sliceLineColor").expect("Line Color has a sentence"); + let first = tab_to_each(&mut a, &ctx, &[numbers, color]); + for ((described, _), sentence) in first.iter().zip([numbers, color]) { + assert_eq!(described.as_deref(), Some(sentence), "the focused control carries the sentence"); } - let described = shown.expect("Tab reaches the Show Slice Numbers row and its sentence shows"); - assert!(described.iter().any(|d| d == numbers), "the focused control carries the sentence: {described:?}"); } /// Whether `sentence` is one of `texts` and is drawn on the description line of the frame that From 29dc2a4ec388b8220cb7e4c6f8c3a46776db7565 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 20 Nov 2026 23:59:24 -0800 Subject: [PATCH 024/151] History: effect steps take the effect's name from the Effect menu History and Edit > Undo/Redo looked a step's label up in the catalog's plain row first, so in catalogs where that row translates the Feather arrowhead (cs, es, fi, fr, hu, id, ka, nl, pl, pt-br) a Feather effect step was named after the arrowhead. Many other effects had a plain row that differed from their menu row too (de Levels), and the Appearance panel showed Inner Glow, Outer Glow, Film Grain and others in English when the catalog had only the menu row. - The engine records which built-in effect a step applied or edited: HistoryEntry::effect(), set through Session::edit_effect around effect.apply, effect.setParams (when every target edits the same effect) and addon.color.filter, and kept through dialog previews, undo and redo. A step another command names like an effect (Object > Transform's Transform) and a step an undo group names keep none. - i18n::effect_menu_label and effect_name give an effect's name from its @id row or the row of its English menu label. The Effect menu, Last Effect, History, Edit > Undo/Redo, the Appearance panel and its effect picker, the effect dialog heading and the Effect Gallery use them. - The untranslated-text report lists missing effect names. --- crates/effects/src/catalog.rs | 6 ++ crates/effects/src/lib.rs | 4 +- crates/engine/src/cmd/addons/color.rs | 2 +- crates/engine/src/cmd/edit.rs | 2 + crates/engine/src/cmd/effectcmd.rs | 72 +++++++------ crates/engine/src/doc_state.rs | 14 ++- crates/engine/src/history.rs | 19 ++++ crates/engine/src/interaction.rs | 3 + crates/engine/src/session/edit.rs | 26 +++++ crates/engine/src/session/execute.rs | 1 + crates/engine/src/tests/history_mem.rs | 40 +++++++ crates/engine/src/tests/textedit.rs | 18 ++++ crates/ui-egui/src/dialogs/effect.rs | 8 +- crates/ui-egui/src/dialogs/effect_gallery.rs | 4 +- crates/ui-egui/src/i18n.rs | 27 +++++ crates/ui-egui/src/i18n/tests.rs | 16 ++- crates/ui-egui/src/menus/labels.rs | 18 ++-- crates/ui-egui/src/panels/appearance.rs | 15 +-- crates/ui-egui/src/panels/history.rs | 104 ++++++++++++++++--- 19 files changed, 324 insertions(+), 75 deletions(-) diff --git a/crates/effects/src/catalog.rs b/crates/effects/src/catalog.rs index 9d9810c240..e0a81abb40 100644 --- a/crates/effects/src/catalog.rs +++ b/crates/effects/src/catalog.rs @@ -875,6 +875,12 @@ pub(crate) fn catalog_index() -> &'static std::collections::HashMap<&'static str INDEX.get_or_init(|| effect_catalog().into_iter().map(|e| (e.id, e)).collect()) } +/// The id and menu label of built-in effect `id`, as the catalogue holds them (no plug-in +/// effects). +pub fn built_in_effect(id: &str) -> Option<(&'static str, &'static str)> { + catalog_index().get(id).map(|e| (e.id, e.label)) +} + /// Catalogue entry for `id` (built-in, or an installed plug-in effect). pub fn effect_info(id: &str) -> Option { catalog_index().get(id).cloned().or_else(|| plugin_info(id)) diff --git a/crates/effects/src/lib.rs b/crates/effects/src/lib.rs index c46ab0c76e..efb7dcfa6a 100644 --- a/crates/effects/src/lib.rs +++ b/crates/effects/src/lib.rs @@ -124,7 +124,9 @@ mod catalog; mod geometry; mod params; -pub use catalog::{EffectInfo, Lengths, WARP_STYLES, effect_catalog, effect_info, is_length, length_range, plugin_effects, raster_px_range}; +pub use catalog::{ + EffectInfo, Lengths, WARP_STYLES, built_in_effect, effect_catalog, effect_info, is_length, length_range, plugin_effects, raster_px_range, +}; pub(crate) use geometry::{Budget, apply_one}; pub use geometry::{ Carry, GeomContext, apply_geometry, apply_geometry_bez, apply_geometry_bez_carrying, apply_geometry_carrying, apply_geometry_with, diff --git a/crates/engine/src/cmd/addons/color.rs b/crates/engine/src/cmd/addons/color.rs index 703d81ddc3..78bbd437e0 100644 --- a/crates/engine/src/cmd/addons/color.rs +++ b/crates/engine/src/cmd/addons/color.rs @@ -173,7 +173,7 @@ fn filter(s: &mut Session, p: &Value) -> Result { let label = effects::effect_info(id).map_or("Apply as Filter", |e| e.label.trim_end_matches('…')); let kinds = effects::addons::duotone::swatch_kinds(&s.doc()?.doc); let swatches = |name: &str| kinds.get(name).copied(); - recolor_links(s, &given, C, label, &|c| map.apply(c), &|c, link, tint| map.apply_link(c, link, tint, &swatches)) + s.edit_effect(id, |s| recolor_links(s, &given, C, label, &|c| map.apply(c), &|c, link, tint| map.apply_link(c, link, tint, &swatches))) } /// Apply Fill to Stroke (`to_stroke`) or Apply Stroke to Fill: each target copies one of its own diff --git a/crates/engine/src/cmd/edit.rs b/crates/engine/src/cmd/edit.rs index ccebbfac88..36a2ac461d 100644 --- a/crates/engine/src/cmd/edit.rs +++ b/crates/engine/src/cmd/edit.rs @@ -808,6 +808,7 @@ fn undo(s: &mut Session, _: &Value) -> Result { let selection = shared_selection(selection, st.history.redo.last()); let mut turned = crate::HistoryEntry::turned(e.label, doc, selection, &st.doc, costs); turned.named = e.named; + turned.effect = e.effect; let paints = e.color_mode_paints.clone(); turned.color_mode_paints = e.color_mode_paints; turned.recost_paints(); @@ -844,6 +845,7 @@ fn redo(s: &mut Session, _: &Value) -> Result { let selection = shared_selection(selection, st.history.undo.last()); let mut turned = crate::HistoryEntry::turned(e.label, doc, selection, &st.doc, costs); turned.named = e.named; + turned.effect = e.effect; let paints = e.color_mode_paints.clone(); turned.color_mode_paints = e.color_mode_paints; turned.recost_paints(); diff --git a/crates/engine/src/cmd/effectcmd.rs b/crates/engine/src/cmd/effectcmd.rs index edb5561796..2fd764fe8f 100644 --- a/crates/engine/src/cmd/effectcmd.rs +++ b/crates/engine/src/cmd/effectcmd.rs @@ -509,11 +509,13 @@ pub(crate) fn apply(s: &mut Session, p: &Value) -> Result { let label = effects::effect_info(id).map(|e| e.label.trim_end_matches('…').to_string()).unwrap_or_default(); aligned(p, C)?; if let Some(loose) = loose_for_pathfinder(s, p, id)? { - let gid = s.edit(&label, |d, sel| { - let gid = super::object::group_nodes(d, &loose)?; - d.node_mut(gid).ok_or(EngineError::NoNode(gid))?.appearance.effects.push(effect.clone()); - sel.set([gid]); - Ok(gid) + let gid = s.edit_effect(id, |s| { + s.edit(&label, |d, sel| { + let gid = super::object::group_nodes(d, &loose)?; + d.node_mut(gid).ok_or(EngineError::NoNode(gid))?.appearance.effects.push(effect.clone()); + sel.set([gid]); + Ok(gid) + }) })?; return Ok(json!({ "ids": [gid.0], "index": 0, "item": null, "grouped": true })); } @@ -544,9 +546,11 @@ pub(crate) fn apply(s: &mut Session, p: &Value) -> Result { } } } - let ids = edit_effects(s, p, item, C, &label, "Apply Effect: select objects", APPENDED, |fx, _| { - fx.push(effect.clone()); - true + let ids = s.edit_effect(id, |s| { + edit_effects(s, p, item, C, &label, "Apply Effect: select objects", APPENDED, |fx, _| { + fx.push(effect.clone()); + true + }) })?; // The item the effect landed on in the object whose row the item is (the first selected object // for the active item, which applies where it fits), and the effect's index in that object. @@ -887,32 +891,36 @@ pub(crate) fn set_params(s: &mut Session, p: &Value) -> Result { } } } - let ids = edit_effects(s, p, item, C, "Effect Options", &format!("{C}: no effect at index {index}"), index, |fx, index| { - let Some(e) = fx.get_mut(index) else { return false }; - if let Some(id) = &warp_id { - e.id.clone_from(id); - } - if let Some(to) = kind - && e.id != to - { - e.params = effects::three_d_params_as(&e.id, &e.params, to); - e.id = to.to_string(); - } - if let (Value::Object(new), cur) = (effects::upgrade_params(&e.id, ¶ms), &mut e.params) { - if !cur.is_object() { - *cur = effects::merged_params(&e.id, &Value::Null); + // The effect edited, when every target has the same one: a dialog's preview names its step after it. + let one = edited.first().filter(|e| edited.iter().all(|other| other == *e)).cloned().unwrap_or_default(); + let ids = s.edit_effect(&one, |s| { + edit_effects(s, p, item, C, "Effect Options", &format!("{C}: no effect at index {index}"), index, |fx, index| { + let Some(e) = fx.get_mut(index) else { return false }; + if let Some(id) = &warp_id { + e.id.clone_from(id); } - // Earlier parameters (a Perspective strength, a light by azimuth and elevation) take - // their current form first, so the new values replace them and the rest is kept. - *cur = effects::upgrade_params(&e.id, cur); - if let Value::Object(m) = cur { - m.extend(new); + if let Some(to) = kind + && e.id != to + { + e.params = effects::three_d_params_as(&e.id, &e.params, to); + e.id = to.to_string(); } - } - if let Some(v) = visible { - e.visible = v; - } - true + if let (Value::Object(new), cur) = (effects::upgrade_params(&e.id, ¶ms), &mut e.params) { + if !cur.is_object() { + *cur = effects::merged_params(&e.id, &Value::Null); + } + // Earlier parameters (a Perspective strength, a light by azimuth and elevation) take + // their current form first, so the new values replace them and the rest is kept. + *cur = effects::upgrade_params(&e.id, cur); + if let Value::Object(m) = cur { + m.extend(new); + } + } + if let Some(v) = visible { + e.visible = v; + } + true + }) })?; Ok(json!({ "ids": ids_json(&ids) })) } diff --git a/crates/engine/src/doc_state.rs b/crates/engine/src/doc_state.rs index cabc774737..7491f39f5c 100644 --- a/crates/engine/src/doc_state.rs +++ b/crates/engine/src/doc_state.rs @@ -52,6 +52,9 @@ pub struct DocState { pub interaction: Option, /// Edits made while this is open are one undo step (a scrubbed numeric field). pub undo_group: Option, + /// The built-in effect the edit in progress applies ([`crate::Session::edit_effect`]): the + /// undo step it records keeps it ([`DocState::push_undo`]). + pub(crate) effect_step: Option<&'static str>, /// For Object → Transform → Transform Again (⌘D): what the last transformation was. A /// transform command keeps the `copy`, `typeAreas` and `patterns` it used, and `strokes` and /// `corners` when it scales; a drag keeps the params of its last preview with the values that @@ -336,6 +339,7 @@ impl DocState { symbol_edit_return: Default::default(), interaction: None, undo_group: None, + effect_step: None, last_transform: None, last_selection_cmd: None, recalled_selection: RecalledSelection::default(), @@ -453,7 +457,9 @@ impl DocState { Some(l) if l.selection == it.selection => l.selection.clone(), _ => it.selection, }; + let effect = std::mem::replace(&mut self.effect_step, it.effect); self.push_undo(it.label, it.doc, selection); + self.effect_step = effect; if let Some(paints) = it.color_mode_paints && let Some(e) = self.history.undo.last_mut() { @@ -469,8 +475,10 @@ impl DocState { } /// Record an undo step: `doc` and `selection` as they were before an edit (the document now is /// the one after it). In an undo group only the group's first edit records one: the edits - /// after it extend that step. + /// after it extend that step. A new step named after the effect in [`DocState::effect_step`] + /// keeps that effect ([`HistoryEntry::effect`]); a step an undo group names keeps none. pub(crate) fn push_undo(&mut self, mut label: String, doc: Arc, selection: Arc) { + let mut effect = self.effect_step; if let Some(g) = &mut self.undo_group { let recorded = |first: &Arc| self.history.undo.last().is_some_and(|l| Arc::ptr_eq(&l.doc, first)); if g.first.as_ref().is_some_and(recorded) { @@ -481,9 +489,11 @@ impl DocState { g.first = Some(doc.clone()); if let Some(l) = &g.label { label = l.clone(); + effect = None; } } - let e = HistoryEntry::kept(label, doc, selection, &self.doc); + let mut e = HistoryEntry::kept(label, doc, selection, &self.doc); + e.effect = effect.filter(|id| crate::history::effect_step_label(id) == Some(e.label.as_str())); self.history.undo.push(e); self.history.clear_redo(); self.history.trim(); diff --git a/crates/engine/src/history.rs b/crates/engine/src/history.rs index d472ec760c..8ec2a5b395 100644 --- a/crates/engine/src/history.rs +++ b/crates/engine/src/history.rs @@ -25,6 +25,9 @@ pub struct HistoryEntry { next: usize, /// The template and name `label` was made from ([`Session::edit_named`]). pub(crate) named: Option, + /// The built-in effect the step applied or edited, when the step is named after it + /// ([`Session::edit_effect`]). + pub(crate) effect: Option<&'static str>, /// A number no other step takes ([`History::step`]). serial: u64, /// Original and changed new-art paints, only for steps that change them: a document color mode @@ -49,6 +52,7 @@ impl Clone for HistoryEntry { next_bytes: self.next_bytes, next: self.next, named: self.named.clone(), + effect: self.effect, serial: self.serial, color_mode_paints: self.color_mode_paints.clone(), color_mode_bytes: self.color_mode_bytes, @@ -63,6 +67,12 @@ fn next_serial() -> u64 { NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed) } +/// The name of the undo step that applies or edits built-in effect `id`: its menu label without +/// the ellipsis. `None` for an id no built-in effect has. +pub(crate) fn effect_step_label(id: &str) -> Option<&'static str> { + vectorcraft_render::effects::built_in_effect(id).map(|(_, label)| label.trim_end_matches('…')) +} + /// A step name made by filling the `{name}` placeholder of a template with a name /// ([`Session::edit_named`]). #[derive(Clone, Debug, PartialEq, Eq)] @@ -95,6 +105,7 @@ impl HistoryEntry { next_bytes, next: std::ptr::from_ref(next) as usize, named: None, + effect: None, serial: next_serial(), color_mode_paints: None, color_mode_bytes: 0, @@ -109,6 +120,13 @@ impl HistoryEntry { self.named.as_ref().filter(|n| n.label() == self.label) } + /// The id of the built-in effect the step applied or edited, while the step's label is still + /// the effect's name: `None` for any other step, and for one whose label was changed since it + /// was recorded. + pub fn effect(&self) -> Option<&'static str> { + self.effect.filter(|id| effect_step_label(id) == Some(self.label.as_str())) + } + /// The step that undoing (redoing) the step `costs` came from makes: it keeps `doc`, the /// document before the undo, whose next state is now `now` (that step's document). Its figures /// are that step's the other way round when `doc` is still the document they were taken @@ -128,6 +146,7 @@ impl HistoryEntry { next_bytes: costs.bytes, next: Arc::as_ptr(now) as usize, named: None, + effect: None, serial: next_serial(), color_mode_paints: None, color_mode_bytes: 0, diff --git a/crates/engine/src/interaction.rs b/crates/engine/src/interaction.rs index 99a2569005..9e0f68c543 100644 --- a/crates/engine/src/interaction.rs +++ b/crates/engine/src/interaction.rs @@ -4,6 +4,9 @@ use super::{Affine, Arc, Document, NodeId, Selection, Value}; #[derive(Clone, Debug)] pub struct Interaction { pub label: String, + /// The built-in effect the last preview applied or edited ([`crate::Session::edit_effect`]): + /// the step the interaction records keeps it when `label` is the effect's name. + pub(crate) effect: Option<&'static str>, pub doc: Arc, /// The selection the previews start from (shared, so a preview frame copies nothing). pub selection: Arc, diff --git a/crates/engine/src/session/edit.rs b/crates/engine/src/session/edit.rs index bbd20fa5bb..5b28f17293 100644 --- a/crates/engine/src/session/edit.rs +++ b/crates/engine/src/session/edit.rs @@ -195,6 +195,29 @@ impl Session { Ok(v) } + /// Run `f`, an edit that applies or edits built-in effect `effect`. The undo step it records, + /// when named after the effect, keeps the effect's id ([`crate::HistoryEntry::effect`]), so a + /// frontend names it as the Effect menu names the effect. Run as an interaction's preview + /// itself, not as one command of a batch the preview runs, the step the interaction records + /// keeps it instead, while that preview is the last one. A later edit of an undo group keeps + /// none. + pub(crate) fn edit_effect(&mut self, effect: &str, f: impl FnOnce(&mut Self) -> Result) -> Result { + let id = vectorcraft_render::effects::built_in_effect(effect).map(|(id, _)| id); + let previewed = self.previewing && self.depth == 1; + let outer = std::mem::replace(&mut self.doc_mut()?.effect_step, id); + let v = f(self); + if let Ok(st) = self.doc_mut() { + st.effect_step = outer; + if v.is_ok() + && previewed + && let Some(it) = &mut st.interaction + { + it.effect = id; + } + } + v + } + /// Change only the selection (not an undo step). pub fn select(&mut self, f: impl FnOnce(&Document, &mut Selection)) -> Result<()> { self.active_appearance_item = None; @@ -297,6 +320,7 @@ impl Session { } st.interaction = Some(Interaction { label: label.to_string(), + effect: None, doc: st.doc.clone(), selection: Arc::new(st.selection.clone()), preview: None, @@ -346,6 +370,8 @@ impl Session { it.color_mode_paints = None; it.deferred_color_mode = None; it.plane_placed = false; + // The effect the preview below applies or edits marks the step, not an earlier one's. + it.effect = None; if selection_changed { st.selection.clone_from(&it.selection); } diff --git a/crates/engine/src/session/execute.rs b/crates/engine/src/session/execute.rs index 046c480079..e86d5aad6c 100644 --- a/crates/engine/src/session/execute.rs +++ b/crates/engine/src/session/execute.rs @@ -403,6 +403,7 @@ impl Session { st.doc = doc; st.selection = selection; st.interaction = interaction; + st.effect_step = None; if let Some(history) = history { st.history = history; } diff --git a/crates/engine/src/tests/history_mem.rs b/crates/engine/src/tests/history_mem.rs index 279020432d..b26f970966 100644 --- a/crates/engine/src/tests/history_mem.rs +++ b/crates/engine/src/tests/history_mem.rs @@ -461,3 +461,43 @@ fn color_mode_paint_snapshots_count_toward_the_history_budget() { original.appearance.unwrap().effects[0].params["retainedTemplateData"] ); } + +/// A step that applies an effect keeps the effect, through undo and redo too. A step named like an +/// effect by anything else keeps none: a plain edit, an undo group named like the effect, and a +/// group another command started that an effect only extends. +#[test] +fn only_steps_an_effect_records_keep_the_effect() { + let mut s = session_with_rects(2); + let last = |s: &Session| s.doc().unwrap().history.undo.last().map(|e| (e.label.clone(), e.effect())); + assert_eq!(last(&s), Some(("Add".into(), None)), "a plain edit named like Pathfinder › Add"); + s.execute("effect.apply", &json!({"effect": "stylize.feather"})).unwrap(); + assert_eq!(last(&s), Some(("Feather".into(), Some("stylize.feather")))); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(s.doc().unwrap().history.redo.last().and_then(|e| e.effect()), Some("stylize.feather"), "an undone step"); + s.execute("edit.redo", &json!({})).unwrap(); + assert_eq!(last(&s), Some(("Feather".into(), Some("stylize.feather"))), "a redone step"); + s.begin_named_undo_group(Some("Feather".into())); + s.execute("effect.apply", &json!({"effect": "stylize.feather"})).unwrap(); + s.end_undo_group(false); + assert_eq!(last(&s), Some(("Feather".into(), None)), "a group named like the effect"); + s.begin_undo_group(); + s.execute("object.transform", &json!({"matrix": [1, 0, 0, 1, 5, 0]})).unwrap(); + s.execute("effect.apply", &json!({"effect": "distort.transform"})).unwrap(); + s.end_undo_group(false); + assert_eq!(last(&s), Some(("Transform".into(), None)), "a group a transform started"); + // An interaction's step keeps the effect its last preview applied, and none when a later + // preview replaced it with another command. + s.begin_interaction("Feather").unwrap(); + s.preview("effect.apply", &json!({"effect": "stylize.feather"})).unwrap(); + s.commit_interaction().unwrap(); + assert_eq!(last(&s), Some(("Feather".into(), Some("stylize.feather"))), "a kept preview"); + s.begin_interaction("Transform").unwrap(); + s.preview("effect.apply", &json!({"effect": "distort.transform"})).unwrap(); + s.preview("object.transform", &json!({"matrix": [1, 0, 0, 1, 5, 0]})).unwrap(); + s.commit_interaction().unwrap(); + assert_eq!(last(&s), Some(("Transform".into(), None)), "a replaced preview"); + s.begin_interaction("Feather").unwrap(); + s.preview("command.batch", &json!({"commands": [{"command": "effect.apply", "params": {"effect": "stylize.feather"}}]})).unwrap(); + s.commit_interaction().unwrap(); + assert_eq!(last(&s), Some(("Feather".into(), None)), "a batch the preview ran"); +} diff --git a/crates/engine/src/tests/textedit.rs b/crates/engine/src/tests/textedit.rs index 8857378855..5c8284ad99 100644 --- a/crates/engine/src/tests/textedit.rs +++ b/crates/engine/src/tests/textedit.rs @@ -3208,6 +3208,24 @@ fn ending_deferred_typing_for_another_edit_keeps_the_typing() { }); } +/// An effect applied while typing waits for its session to end keeps the typing as its own step +/// first, and the effect's own step still keeps the effect it applied. +#[test] +fn an_effect_applied_while_typing_waits_keeps_its_effect_on_its_step() { + let mut s = session(); + s.prefs.real_time_drawing = false; + let v = ViewInfo::default(); + let id = text(&mut s, "Hello"); + s.select_tool("type", v).unwrap(); + let b = s.doc().unwrap().doc.bounds_of(&[id], false).unwrap(); + click(&mut s, b.x1 - 1.0, b.center().y); + s.tool_text(" world", v).unwrap(); + s.execute("effect.apply", &json!({"effect": "stylize.feather", "ids": [id.0]})).unwrap(); + assert_eq!(undo_labels(&s).iter().rev().take(2).collect::>(), ["Feather", "Typing"]); + let h = s.doc().unwrap().history.undo.last().unwrap(); + assert_eq!(h.effect(), Some("stylize.feather")); +} + /// #1950: a colour previewed while typing (the Color Picker, a Color panel slider) colours the /// typed text: its interaction used to join the typing session and preview from the document /// before the typing, so the new type came back as its placeholder text. diff --git a/crates/ui-egui/src/dialogs/effect.rs b/crates/ui-egui/src/dialogs/effect.rs index df5789e649..094d703206 100644 --- a/crates/ui-egui/src/dialogs/effect.rs +++ b/crates/ui-egui/src/dialogs/effect.rs @@ -67,16 +67,14 @@ fn three_d_refusal(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog, } } -/// The effect's name (`__label`, English) in the UI language: the catalog may carry it with or -/// without its trailing ellipsis. A plug-in effect's name is shown as it is. +/// The effect's name in the UI language as the Effect menu shows it ([`crate::i18n::effect_name`] +/// of `__effect`), else `__label` as it is. A plug-in effect's name is shown as it is. fn heading_label(d: &Dialog) -> String { let label = d.str("__label"); if vectorcraft_plugins::effect::plugin_id(&d.str("__effect")).is_some() { return label; } - let dotted = format!("{label}…"); - let shown = tl!(&dotted); - if shown != dotted { shown.trim_end_matches('…').to_string() } else { tl!(&label).to_string() } + crate::i18n::effect_name(crate::i18n::current(), &d.str("__effect")).unwrap_or(label) } /// The dialog kind asking whether to edit an effect that is already applied or add another. diff --git a/crates/ui-egui/src/dialogs/effect_gallery.rs b/crates/ui-egui/src/dialogs/effect_gallery.rs index 39c2dc6c7c..874562245d 100644 --- a/crates/ui-egui/src/dialogs/effect_gallery.rs +++ b/crates/ui-egui/src/dialogs/effect_gallery.rs @@ -368,7 +368,7 @@ fn stack_preview_row(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog } fn effect_label(id: &str) -> String { - vectorcraft_effects::effect_info(id).map(|e| tl!(e.label).trim_end_matches('…').to_string()).unwrap_or_else(|| id.to_string()) + crate::i18n::effect_name(crate::i18n::current(), id).unwrap_or_else(|| id.to_string()) } /// Where the preview rasters sit: one document point per pixel, origin at the top-left. @@ -614,7 +614,7 @@ fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { egui::ScrollArea::vertical().max_height(240.0).show(ui, |ui| { for e in &effects { let picked = e.id == sel; - let name = tl!(e.label).trim_end_matches('…').to_string(); + let name = effect_label(e.id); let image = egui::Image::from_texture(&thumb_tex(ui.ctx(), e.id)).fit_to_exact_size(egui::vec2(THUMB as f32, THUMB as f32)); #[cfg(test)] THUMBS_PAINTED.with(|c| c.set(c.get() + 1)); diff --git a/crates/ui-egui/src/i18n.rs b/crates/ui-egui/src/i18n.rs index eb9a7b10ec..980bbf2785 100644 --- a/crates/ui-egui/src/i18n.rs +++ b/crates/ui-egui/src/i18n.rs @@ -662,6 +662,33 @@ pub fn t_id<'a>(id: &str, label: &'a str) -> &'a str { tr_id(current(), id, label) } +/// The Effect menu's label of effect `id` in `lang`: an `@id` row for the effect's id, else the +/// row of its English menu label. A plug-in effect's label is the plug-in's own text. `None` for +/// an id that names no effect. The Effect menu, History, Edit › Undo and Redo, the Appearance +/// panel and the effect dialogs all name an effect through this lookup. +pub fn effect_menu_label(lang: Lang, id: &str) -> Option { + match built_in_effect_label(id) { + Some(label) => Some(tr_id(lang, id, label).to_string()), + None => vectorcraft_plugins::effect::plugin_id(id).and_then(|_| vectorcraft_effects::effect_info(id)).map(|info| info.label.to_string()), + } +} + +/// [`effect_menu_label`] without its trailing ellipsis: an effect's name in `lang`. +pub fn effect_name(lang: Lang, id: &str) -> Option { + effect_menu_label(lang, id).map(|s| s.trim_end_matches('…').to_string()) +} + +/// Does `lang`'s catalog name built-in effect `id`: an `@id` row for the id, or a row for its +/// English menu label? +pub fn has_effect_name(lang: Lang, id: &str) -> bool { + built_in_effect_label(id).is_some_and(|label| lang.catalog().id(id).is_some() || has(lang, label)) +} + +/// The English Effect menu label of built-in effect `id`. +fn built_in_effect_label(id: &str) -> Option<&'static str> { + vectorcraft_effects::built_in_effect(id).map(|(_, label)| label) +} + /// Fill `{name}` placeholders. Unknown placeholders are left as written. pub fn fmt(template: &str, args: &[(&str, &str)]) -> String { let mut out = template.to_string(); diff --git a/crates/ui-egui/src/i18n/tests.rs b/crates/ui-egui/src/i18n/tests.rs index 2ca2c76e03..8c0e0587dc 100644 --- a/crates/ui-egui/src/i18n/tests.rs +++ b/crates/ui-egui/src/i18n/tests.rs @@ -2456,14 +2456,15 @@ fn untranslated_report() { assert!(strings.len() > 500, "menu scan found only {} strings", strings.len()); let literals = tl_literals(); assert!(literals.len() > 300, "scan found only {} tl! literals", literals.len()); - // Undo step names: the recorded names, every effect's name without its ellipsis, and the - // Liquify tools' step names (`{} Tool`). A name's row is its plain row or the row of the same - // name with an ellipsis (`panels::history::step_name`); a template made with - // `Session::edit_named` needs a plain row, which `panels::history::entry_name` fills. + // Undo step names: the recorded names and the Liquify tools' step names (`{} Tool`). A name's + // row is its plain row or the row of the same name with an ellipsis + // (`panels::history::step_name`); a template made with `Session::edit_named` needs a plain + // row, which `panels::history::entry_name` fills. A step that applies an effect is named as + // the Effect menu names it (`i18n::has_effect_name`), listed under "effect names". let scan = undo_scan(); let mut undo = scan.labels; assert!(undo.len() > 300, "scan found only {} undo labels", undo.len()); - undo.extend(vectorcraft_effects::effect_catalog().iter().map(|e| e.label.trim_end_matches('…').to_string())); + let effect_ids: Vec<&'static str> = vectorcraft_effects::effect_catalog().iter().map(|e| e.id).collect(); let liquify = ["warp", "twirl", "pucker", "bloat", "scallop", "crystallize", "wrinkle"]; undo.extend(liquify.iter().filter_map(|k| vectorcraft_tools::distort::liquify::LiquifyKind::parse(k)).map(|k| format!("{} Tool", k.label()))); assert_eq!(scan.formatted.iter().collect::>(), ["{} Tool"], "step names built with format! (make them with Session::edit_named)"); @@ -2488,6 +2489,11 @@ fn untranslated_report() { add(l.code, "menu strings", strings.iter().filter(|s| !kept(s) && cat.plain(s).is_none()).cloned().collect::>()); add(l.code, "tl! strings", literals.iter().filter(|s| cat.plain(s).is_none()).cloned().collect::>()); add(l.code, "undo labels", undo.iter().filter(|s| crate::panels::history::step_name(lang, s).is_none()).cloned().collect::>()); + add( + l.code, + "effect names", + effect_ids.iter().filter(|id| !crate::i18n::has_effect_name(lang, id)).map(|id| id.to_string()).collect::>(), + ); add(l.code, "undo label templates", scan.templates.iter().filter(|t| cat.plain(t).is_none()).cloned().collect::>()); let (entries, _) = parse_entries(l.source); let rows: BTreeSet<(&str, &str)> = entries.iter().map(|(ctx, src, _)| (ctx.as_str(), src.as_str())).collect(); diff --git a/crates/ui-egui/src/menus/labels.rs b/crates/ui-egui/src/menus/labels.rs index 61a4bf5872..dd73c842f7 100644 --- a/crates/ui-egui/src/menus/labels.rs +++ b/crates/ui-egui/src/menus/labels.rs @@ -187,8 +187,8 @@ pub fn display_label(app: &VectorcraftApp, id: &str, label: &str) -> String { } "effect.last" => match &app.last_effect { Some((e, _)) => { - let name = vectorcraft_effects::effect_info(e).map(|i| i.label).unwrap_or(e.as_str()); - fmt(tl!("Last Effect: {name}"), &[("name", crate::i18n::tr_id(lang, e, name))]) + let name = crate::i18n::effect_menu_label(lang, e).unwrap_or_else(|| e.clone()); + fmt(tl!("Last Effect: {name}"), &[("name", &name)]) } None => crate::i18n::tr_id(lang, id, label).to_string(), }, @@ -199,17 +199,19 @@ pub fn display_label(app: &VectorcraftApp, id: &str, label: &str) -> String { } } -/// The label of an Effect menu item in the UI language, by the effect's own id. Every effect item -/// runs `effect.apply` or `effect.dialog`, so the command id can't tell them apart; an `@id` row -/// for the effect id (for example `pathfinder.add`) wins over the plain row of the English label. -/// `None` when the catalog has no such row, and the plain translation applies. +/// The label of an Effect menu item in the UI language, by the effect's own id +/// ([`crate::i18n::effect_menu_label`]). Every effect item runs `effect.apply` or `effect.dialog`, +/// so the command id can't tell them apart. `None` for any other item, and for a plug-in effect, +/// whose item shows the plug-in's own text. pub(super) fn effect_item_label(id: &str, p: &Value) -> Option { if !matches!(id, "effect.apply" | "effect.dialog") { return None; } let effect = p.get("effect")?.as_str()?; - let shown = crate::i18n::tr_id(crate::i18n::current(), effect, ""); - (!shown.is_empty()).then(|| shown.to_string()) + if vectorcraft_plugins::effect::plugin_id(effect).is_some() { + return None; + } + crate::i18n::effect_menu_label(crate::i18n::current(), effect) } /// The label of an item of the canvas context menu's Unlock submenu (`layer.setProps` with one id diff --git a/crates/ui-egui/src/panels/appearance.rs b/crates/ui-egui/src/panels/appearance.rs index 52b36b4535..fe843d00e5 100644 --- a/crates/ui-egui/src/panels/appearance.rs +++ b/crates/ui-egui/src/panels/appearance.rs @@ -242,11 +242,11 @@ fn built_in_effect(id: &str) -> bool { catalog().iter().any(|c| c.0 == id) } -/// [`effect_label`] as shown: a built-in effect's in the UI language (an `@id` row for the -/// effect's id wins over the plain row of its English label), a plug-in's as it is. +/// [`effect_label`] as shown: a built-in effect's name in the UI language as the Effect menu +/// shows it ([`crate::i18n::effect_name`]), a plug-in's as it is. pub(crate) fn shown_effect_label(id: &str) -> String { - match catalog().iter().find(|c| c.0 == id) { - Some(c) => crate::i18n::t_id(id, &c.1).to_string(), + match built_in_effect(id).then(|| crate::i18n::effect_name(crate::i18n::current(), id)).flatten() { + Some(name) => name, None => effect_label(id), } } @@ -1816,9 +1816,10 @@ fn delete_selected(app: &mut VectorcraftApp, ui: &Ui, node: Option<&Node>, sel: pub(crate) fn fx_menu(app: &mut VectorcraftApp, ui: &mut Ui) { let mut groups: Vec<(String, Vec<(String, String)>)> = vec![]; let plugins: Vec<_> = vectorcraft_effects::plugin_effects().into_iter().map(catalog_entry).collect(); - // Built-in effects in the UI language; a plug-in's by the name it gives. - let built_in = catalog().iter().map(|(id, label, menu)| (id, tl!(label), menu)); - for (id, label, menu) in built_in.chain(plugins.iter().map(|(id, label, menu)| (id, label.as_str(), menu))) { + // Built-in effects named as the Effect menu names them; a plug-in's by the name it gives. + let lang = crate::i18n::current(); + let built_in = catalog().iter().map(|(id, label, menu)| (id, crate::i18n::effect_name(lang, id).unwrap_or_else(|| label.clone()), menu)); + for (id, label, menu) in built_in.chain(plugins.iter().map(|(id, label, menu)| (id, label.clone(), menu))) { let g = menu.get(1).cloned().unwrap_or_else(|| "Other".into()); match groups.iter_mut().find(|(n, _)| *n == g) { Some((_, v)) => v.push((id.clone(), label.to_string())), diff --git a/crates/ui-egui/src/panels/history.rs b/crates/ui-egui/src/panels/history.rs index cc0c609868..b75b831d1c 100644 --- a/crates/ui-egui/src/panels/history.rs +++ b/crates/ui-egui/src/panels/history.rs @@ -27,10 +27,15 @@ pub fn step_name(lang: crate::i18n::Lang, label: &str) -> Option { /// A step's name in `lang`. A name made from a template (`Apply {name}`, /// [`vectorcraft_engine::HistoryEntry::named`]) takes the template's plain row with the name in its /// placeholder. A name VectorCraft gives is shown in `lang`, and any other name is shown as the -/// document holds it. It returns `None` when the catalog has no row for the template. Any other step -/// takes [`step_name`] of its label. +/// document holds it. It returns `None` when the catalog has no row for the template. A step that +/// applied or edited a built-in effect ([`vectorcraft_engine::HistoryEntry::effect`]) takes the +/// effect's name as the Effect menu shows it ([`crate::i18n::effect_name`]), `None` when the +/// catalog has no row for it. Any other step takes [`step_name`] of its label. pub fn entry_name(lang: crate::i18n::Lang, h: &vectorcraft_engine::HistoryEntry) -> Option { - use crate::i18n::{fmt, has, label_or_name, tr}; + use crate::i18n::{effect_name, fmt, has, has_effect_name, label_or_name, tr}; + if let Some(effect) = h.effect() { + return has_effect_name(lang, effect).then(|| effect_name(lang, effect)).flatten(); + } match h.named() { Some(n) => has(lang, n.template).then(|| fmt(tr(lang, n.template), &[("name", label_or_name(lang, &n.name, n.built_in))])), None => step_name(lang, &h.label), @@ -183,20 +188,95 @@ mod tests { assert_eq!(listed(&mut app)[rows.len() - 6..rows.len() - 4], ["Apply Body", "Apply {name}"]); } - /// A step named after an effect whose catalog row has only the menu label with its ellipsis - /// takes that row's translation without the ellipsis; a name with no row has none. + /// A step name with no catalog row has no translation. #[test] - fn effect_steps_read_the_menu_row() { + fn unknown_steps_have_no_name() { let ja = crate::i18n::Lang::from_code("ja").expect("ja registered"); - for effect in ["Revolve", "Feather"] { - let menu_row = - crate::i18n::has(ja, &format!("{effect}…")).then(|| crate::i18n::tr(ja, &format!("{effect}…")).trim_end_matches('…').to_string()); - let plain_row = crate::i18n::has(ja, effect).then(|| crate::i18n::tr(ja, effect).to_string()); - assert_eq!(step_name(ja, effect), plain_row.or(menu_row), "{effect}"); - } assert_eq!(step_name(ja, "No Such Step"), None); } + /// Every built-in effect has one name in each language: History (and Edit › Undo and Redo) + /// names the step that applied it, and the Appearance panel its row, with the text of its + /// Effect menu item without the ellipsis, which is the effect's `@id` row or the row of its + /// menu label with the ellipsis. + #[test] + fn effects_have_the_same_name_in_history_appearance_and_the_effect_menu() { + let mut app = app_with_two_rectangles(); + // The step each effect that applies to a rectangle with its defaults records. + let mut steps = Vec::new(); + for e in vectorcraft_effects::effect_catalog() { + if app.session.execute("effect.apply", &json!({ "effect": e.id })).is_ok() { + let h = app.session.active().unwrap().history.undo.last().cloned().unwrap(); + assert_eq!(h.effect(), Some(e.id), "{} names its step after the effect", e.id); + steps.push((e, h)); + app.session.execute("edit.undo", &json!({})).unwrap(); + } + } + assert!(steps.len() * 2 > vectorcraft_effects::effect_catalog().len(), "only {} effects applied", steps.len()); + let mut differ = Vec::new(); + for lang in crate::i18n::Lang::all() { + crate::i18n::set_current(lang); + for (e, h) in &steps { + let cmd = if e.defaults.as_object().is_some_and(|o| o.is_empty()) { "effect.apply" } else { "effect.dialog" }; + let item = crate::menus::shown_label(&app, cmd, &json!({ "effect": e.id }), e.label); + let menu = item.trim_end_matches('…'); + let row = crate::i18n::tr_id(lang, e.id, e.label).trim_end_matches('…').to_string(); + let step = shown(h); + let shown_row = super::super::appearance::shown_effect_label(e.id); + if menu != row || step != menu || shown_row != menu { + differ.push(format!("{} {}: catalog {row:?}, menu {menu:?}, History {step:?}, Appearance {shown_row:?}", lang.code(), e.id)); + } + } + } + crate::i18n::set_current(crate::i18n::Lang::EN); + assert!(differ.is_empty(), "{differ:#?}"); + } + + /// A step another command names like an effect (Object › Transform's `Transform`, the name of + /// Distort & Transform › Transform) keeps its own name in every language. + #[test] + fn a_step_named_like_an_effect_keeps_its_own_name() { + let mut app = app_with_two_rectangles(); + app.session.execute("object.transform", &json!({ "matrix": [1, 0, 0, 1, 5, 0] })).unwrap(); + let h = app.session.active().unwrap().history.undo.last().cloned().unwrap(); + assert_eq!((h.label.as_str(), h.effect()), ("Transform", None)); + for lang in crate::i18n::Lang::all() { + assert_eq!(entry_name(lang, &h), step_name(lang, "Transform"), "{}", lang.code()); + } + } + + /// The Feather dialog's preview, kept with OK, records a step that History and Edit › Undo and + /// Redo name as the Effect menu names Feather, in French as in English. + #[test] + fn an_effect_kept_from_its_dialog_preview_is_named_after_the_effect() { + let fr = crate::i18n::Lang::from_code("fr").expect("fr registered"); + let mut app = app_with_two_rectangles(); + crate::i18n::set_current(fr); + let item = crate::menus::shown_label(&app, "effect.dialog", &json!({ "effect": "stylize.feather" }), "Feather…"); + crate::i18n::set_current(crate::i18n::Lang::EN); + let menu = item.trim_end_matches('…').to_string(); + let frame = |app: &mut VectorcraftApp, events: Vec| { + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + let mut out = ctx.run_ui(egui::RawInput { events, ..Default::default() }, |ui| crate::dialogs::show(app, ui.ctx())); + out.textures_delta.clear(); + }; + app.run("effect.dialog", json!({ "effect": "stylize.feather", "item": null })).unwrap(); + frame(&mut app, vec![]); + assert!(app.session.in_interaction(), "the dialog previews"); + let enter = egui::Event::Key { key: egui::Key::Enter, physical_key: None, pressed: true, repeat: false, modifiers: Default::default() }; + frame(&mut app, vec![enter]); + assert!(app.ui.dialog.is_none(), "OK closed the dialog"); + let h = app.session.active().unwrap().history.undo.last().cloned().unwrap(); + assert_eq!(h.effect(), Some("stylize.feather")); + app.session.execute("edit.undo", &json!({})).unwrap(); + let undone = app.session.active().unwrap().history.redo.last().cloned().unwrap(); + crate::i18n::set_current(fr); + let names = (shown(&h), shown(&undone)); + crate::i18n::set_current(crate::i18n::Lang::EN); + assert_eq!(names, (menu.clone(), menu), "the step, and the step undone"); + } + fn app_with_two_rectangles() -> VectorcraftApp { let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); app.session.execute("file.new", &json!({"width": 200, "height": 150})).unwrap(); From 5e30728f4dfa2c595f18b29eb319f14d5a0404ca Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 00:04:51 -0800 Subject: [PATCH 025/151] Save PDF: a settings object set by ui.dialog.set keeps the options it leaves out `ui.dialog.set` replaced a Save PDF settings object (`bleed`, `marks`, `compression` and the others) with the value given. Options left out then showed the default settings in the dialog, while Save PDF took them from the chosen preset. With the bleed, the link copied the default top value to the other sides while the file kept the preset's top: from a preset with `[3, 5, 3, 3]`, `{"useDocument": false}` followed by linking wrote `[3, 0, 0, 0]`. - A settings object set there now sets only the options it holds; the ones it leaves out keep the dialog's values. A null option is still set as given. - A value that is not an object is refused, and the request leaves the dialog as it was. - A test sends a request that sets `bleed` and then an invalid `__bleedLinked` through the control handler and checks the dialog is unchanged. --- crates/ui-egui/src/dialogs.rs | 7 +- crates/ui-egui/src/dialogs/save_pdf.rs | 34 ++++++++- crates/ui-egui/src/dialogs/save_pdf/tests.rs | 80 ++++++++++++++++++++ docs/control-protocol.md | 2 +- 4 files changed, 117 insertions(+), 6 deletions(-) diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index a24755ab12..ed805635bc 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -734,8 +734,9 @@ pub(crate) fn parent(d: &Dialog) -> Option { /// to Export for Screens' sub-folder controls ends an applied preset's item folders, as it does in /// the dialog, Transform Each's Relative / Absolute keeps the Scale fields' size, and Recolor /// Artwork's `group` selects that color group and its `groupAction` runs the button at once. Save -/// PDF's bleed link links the bleed as its button does. A value Composite Fonts' Show Sample or -/// Save PDF's bleed link can't take is refused. +/// PDF's bleed link links the bleed as its button does, and a Save PDF settings object sets only the +/// options it holds. A value Composite Fonts' Show Sample, Save PDF's bleed link or a Save PDF +/// settings object can't take is refused. pub(crate) fn field_set(app: &mut VectorcraftApp, field: &str, old: Option<&Value>) -> Result<(), String> { if app.ui.dialog.as_ref().is_some_and(|d| d.kind == transform_each::KIND) { transform_each::field_set(app, field, old); @@ -748,7 +749,7 @@ pub(crate) fn field_set(app: &mut VectorcraftApp, field: &str, old: Option<&Valu return composite_fonts::field_set(d, field); } if let Some(d) = app.ui.dialog.as_mut().filter(|d| d.kind == save_pdf::KIND || d.kind == save_pdf::PRESET_KIND) { - return save_pdf::field_set(d, field); + return save_pdf::field_set(d, field, old); } if let Some(d) = app.ui.dialog.as_mut().filter(|d| d.kind == eps_options::KIND) { eps_options::field_set(d, field); diff --git a/crates/ui-egui/src/dialogs/save_pdf.rs b/crates/ui-egui/src/dialogs/save_pdf.rs index a8db555bfb..75f9c7179f 100644 --- a/crates/ui-egui/src/dialogs/save_pdf.rs +++ b/crates/ui-egui/src/dialogs/save_pdf.rs @@ -801,8 +801,13 @@ fn edit_bleed(d: &mut Dialog, side: usize, value: f64) { /// `ui.dialog.set` set `field` of Save PDF or the PDF preset editor: `__bleedLinked` links or /// unlinks the bleed as its button does, and must be true or false; every write of `bleed`, the /// same values included, drops the link's state, so the link follows the values set. A flattener -/// preset set there drops the Custom… options, as choosing it in the dropdown does. -pub(super) fn field_set(d: &mut Dialog, field: &str) -> Result<(), String> { +/// preset set there drops the Custom… options, as choosing it in the dropdown does. A settings +/// object (`bleed`, `marks`, `compression`…) set there must be an object and sets only the options +/// it holds: the ones it leaves out keep the values the dialog had (`old`). +pub(super) fn field_set(d: &mut Dialog, field: &str, old: Option<&Value>) -> Result<(), String> { + if DEFAULTS.get(field).is_some_and(Value::is_object) { + keep_unset_options(d, field, old)?; + } match field { BLEED_LINKED => match d.fields.get(BLEED_LINKED).cloned() { Some(Value::Bool(on)) => { @@ -823,6 +828,31 @@ pub(super) fn field_set(d: &mut Dialog, field: &str) -> Result<(), String> { } } +/// The settings object `field` that `ui.dialog.set` set, with the options it leaves out taken from +/// `old` (the default settings' when the dialog had none). A null is kept as it was set. +fn keep_unset_options(d: &mut Dialog, field: &str, old: Option<&Value>) -> Result<(), String> { + let Some(new) = d.fields.get_mut(field).filter(|v| !v.is_null()) else { return Ok(()) }; + if !new.is_object() { + return Err(format!("{field} must be an object of options, not {new}")); + } + let mut merged = old.filter(|o| o.is_object()).or_else(|| DEFAULTS.get(field)).cloned().unwrap_or_default(); + merge_options(&mut merged, new); + *new = merged; + Ok(()) +} + +/// Set the options `over` holds on `base`, object by object. +fn merge_options(base: &mut Value, over: &Value) { + match (base, over) { + (Value::Object(b), Value::Object(o)) => { + for (k, v) in o { + merge_options(b.entry(k.as_str()).or_insert(Value::Null), v); + } + } + (b, o) => *b = o.clone(), + } +} + /// A dropdown of names such as colour profiles or flattener presets (`names`, the first one /// standing for "" at `path`), showing the name at `path` (one that isn't among them too). The /// first `builtins` entries are ours (translated); the others (profiles, saved presets) are names. diff --git a/crates/ui-egui/src/dialogs/save_pdf/tests.rs b/crates/ui-egui/src/dialogs/save_pdf/tests.rs index 501aed4ed0..d59c2eea4b 100644 --- a/crates/ui-egui/src/dialogs/save_pdf/tests.rs +++ b/crates/ui-egui/src/dialogs/save_pdf/tests.rs @@ -1011,6 +1011,86 @@ fn ui_dialog_set_links_the_bleed() { assert!(!bleed_linked(d) && bleed_of(d) == [1.0; 4], "a later __bleedLinked unlinks them"); } +/// `ui.dialog.set` with `fields`, as a control request. +fn dialog_set(app: &mut VectorcraftApp, fields: Value) -> Value { + let (req, _) = crate::control::ControlRequest::new("ui.dialog.set", json!({ "fields": fields })); + let crate::control::Outcome::Done(r) = crate::control::handle(app, &egui::Context::default(), &req) else { panic!("not done") }; + r +} + +/// The open dialog as JSON, to compare it before and after a request. +fn dialog_json(app: &VectorcraftApp) -> Value { + serde_json::to_value(app.ui.dialog.as_ref()).unwrap() +} + +/// A settings object `ui.dialog.set` sets with some of its options changes only those: the +/// others keep the dialog's values, so the dialog shows what Save PDF writes and the bleed link +/// gives every side the top value Save PDF writes. +#[test] +fn ui_dialog_set_keeps_the_options_a_settings_object_leaves_out() { + let (mut app, _, _) = app(); + app.run("pdf.preset.save", json!({"name": "Uneven", "bleed": {"top": 3, "bottom": 5, "left": 3, "right": 3}})).unwrap(); + app.run("pdf.preset.save", json!({"name": "Marked", "marks": {"trim": true, "offset": 9}})).unwrap(); + app.run("ui.savePdfDialog", json!({"preset": "Uneven"})).unwrap(); + + let r = dialog_set(&mut app, json!([{"field": "bleed", "value": {"useDocument": false}}])); + assert_eq!(r["ok"], true, "{r}"); + let d = app.ui.dialog.as_ref().unwrap(); + assert!(bleed_of(d) == [3.0, 5.0, 3.0, 3.0] && !bleed_linked(d), "the sides left out keep their values"); + let r = dialog_set(&mut app, json!([{"field": BLEED_LINKED, "value": true}])); + assert_eq!(r["ok"], true, "{r}"); + let d = app.ui.dialog.as_ref().unwrap(); + assert_eq!(bleed_of(d), [3.0; 4], "linking gives every side the top value"); + assert_eq!(params(d)["bleed"], json!({"useDocument": false, "top": 3.0, "bottom": 3.0, "left": 3.0, "right": 3.0})); + + let r = dialog_set(&mut app, json!([{"field": "bleed", "value": {"bottom": 5}}])); + assert_eq!(r["ok"], true, "{r}"); + assert_eq!(bleed_of(app.ui.dialog.as_ref().unwrap()), [3.0, 5.0, 3.0, 3.0], "only the side set changes"); + + // A null option is set as it is: a null `output.profiles` still leaves the profiles unset. + let r = dialog_set(&mut app, json!([{"field": "output", "value": {"profiles": "all"}}])); + assert_eq!(r["ok"], true, "{r}"); + let r = dialog_set(&mut app, json!([{"field": "output", "value": {"profiles": null}}])); + assert_eq!(r["ok"], true, "{r}"); + let d = app.ui.dialog.as_ref().unwrap(); + assert!(get(d, "output.profiles").is_null() && get(d, "output.conversion") == &json!("none"), "{:?}", d.fields.get("output")); + + // Every settings object, not only the bleed. + app.run("ui.savePdfDialog", json!({"preset": "Marked"})).unwrap(); + let r = dialog_set(&mut app, json!([{"field": "marks", "value": {"weight": 0.5}}])); + assert_eq!(r["ok"], true, "{r}"); + let d = app.ui.dialog.as_ref().unwrap(); + assert_eq!((get(d, "marks.trim"), get(d, "marks.offset"), get(d, "marks.weight")), (&json!(true), &json!(9.0), &json!(0.5))); + + // A value that isn't an object is refused, and the dialog stays as it was. + let before = dialog_json(&app); + for bad in [json!(5), json!("3 mm"), json!([3, 3, 3, 3])] { + let r = dialog_set(&mut app, json!([{"field": "bleed", "value": bad}])); + assert_eq!(r["ok"], false, "{bad}: {r}"); + assert!(r["error"].as_str().is_some_and(|e| e.contains("bleed must be an object of options")), "{bad}: {r}"); + assert_eq!(dialog_json(&app), before, "{bad}"); + } +} + +/// A `ui.dialog.set` request whose later field is refused leaves the whole dialog as it was +/// before the request, the bleed values an earlier field set included. +#[test] +fn a_refused_bleed_link_leaves_the_whole_request_unset() { + let (mut app, _, _) = app(); + app.run("ui.savePdfDialog", json!({"bleed": {"top": 3, "bottom": 3, "left": 3, "right": 3}})).unwrap(); + let before = dialog_json(&app); + let r = dialog_set( + &mut app, + json!([ + {"field": "bleed", "value": {"top": 1, "bottom": 2, "left": 3, "right": 4}}, + {"field": BLEED_LINKED, "value": "yes"}, + ]), + ); + assert_eq!(r["ok"], false, "{r}"); + assert!(r["error"].as_str().is_some_and(|e| e.contains("__bleedLinked must be true or false")), "{r}"); + assert_eq!(dialog_json(&app), before, "the dialog is unchanged"); +} + /// An unlinked edit that makes the four sides equal leaves the link off, so the next edit /// changes one side only. #[test] diff --git a/docs/control-protocol.md b/docs/control-protocol.md index dafab93a58..4df97a70b7 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -110,7 +110,7 @@ the two can still win that race. | `app.open` / `app.save` / `app.export` / `app.quit` | `{path, importer?, params?}` / `{path?}` / `{path?, format?, artboard?, range?, scale?, …}` | `app.open` reads every format `document.open` reads (see `document.formats`) and returns its result (`{index, title, format, warnings, …}`; `warnings` say what didn't come in as it was, such as an EPS shown as its preview image and why its PostScript couldn't be read), or null when a dialog asks first or a library loads. The status bar (`ui.inspect` → `ui.status`), after a line about the document's linked files when there is one (Missing linked files below), counts the `warnings` and names the first that says reading the file left something out (the notes that make Save ask before writing over it), else the first; with several, hovering it lists them in that order, as many as fit in the window (at most 30), then how many more. After `app.save`, and `app.export` with a `path`, the status bar counts the reply's `warnings` and names the first, and with several, hovering it lists them in the reply's order (a save's notes start with what the format loses). With `importer` (an importer plug-in's format id, `plugin.`) it runs `file.openWith`: the file opens with that importer, also when a built-in format reads its extension, with the importer's parameters `params` (their defaults when omitted; no dialog asks for them). Without `importer`, `params` go to the importer that opens the file, and a built-in format does not read them. `app.export` encodes through the engine's `document.export` (same options; the document keeps its path) and writes `path` through the host; without `path` it returns `{dataBase64, format, bytes}`, as headless mode does. It refuses a key that no format takes, and an unknown key inside a PDF or EPS option object, before it writes anything (`docs/mcp.md`, Parameter keys). It accepts a key that only another format takes and does not use it: the reply's `warnings` and the status bar name the key ("`quality` was not used: PDF files don't read it"). `app.save` refuses a key that no save format takes, beside the path or in `options`, the same way. `app.quit`, `file.close` and `file.closeAll` first open a `saveChanges` dialog for each modified document (they return `{"pending": "saveChanges"}`): `ui.dialog.confirm` saves, `ui.dialog.set {field: "discard", value: true}` then confirm discards, `ui.dialog.cancel` cancels the whole close or quit | | `app.export` with `useArtboards` | `{path, useArtboards: true, range? \| artboards?, …}` | Export As: PNG, JPEG and WebP write one file per chosen artboard (default all; SVG does so for a `range`), `-.`, and return `{path, files: [path…]}`; a PDF keeps them as pages of `path`. `useArtboards: false` covers the bounds of the visible art. The menu's Export As… is `file.exportAs`: the `exportAs` dialog (`format`, `useArtboards`, `all`, `range`), then a save dialog and the format's options: `pngOptions` / `jpgOptions` / `webpOptions`, `svgOptions`, or `savePdf` for a PDF | | `ui.dialog.*` on `gradientStop` | `{field: "color" \| "opacity" \| "location", value}` | double-clicking a stop on the Gradient tool's annotator opens its popover (fields `index`, `x`, `y`, `tab`); set `color` (hex), `opacity` or `location` (percentages) and `ui.dialog.confirm` to apply them to the selected stop. `gradient.selectStop {index}` picks the stop the annotator, the panels and Delete/←/→ (`ui.key`) act on | -| `engine.execute` `ui.savePdfDialog` | `{path?, preset?, range?, …document.exportPdf options}` | opens the Save PDF dialog (`file.export.pdf` with no params opens it too). Its fields are the `document.exportPdf` options: set `compatibility` with `ui.dialog.set {field: "compatibility", value: "1.5"}`, a whole section with `{field: "compression", value: {…}}`, the artboards with `__allArtboards: false` and `range`, the visible section with `__section` (General, Compression, Marks and Bleeds, Output, Advanced, Security, Summary), and the bleed link with `__bleedLinked` (true gives every side the top value; any value other than true or false is an error; setting `bleed` turns the link on when its four sides are equal and off when they differ). In Advanced, Custom… beside Flattener preset (enabled when the file is flattened: PDF 1.3, PDF/X-1a, PDF/X-3) opens the `pdfFlattenerOptions` dialog over Save PDF on the flattener options the save would use; its fields are those options, with `clipComplexRegions`, `preserveAlpha` and `preserveOverprints` set by the writer and Overprint. Its `ui.dialog.confirm` sets `flattener` (the preset then shows [Custom]; options equal to the preset's leave it unset) and goes back to Save PDF, and `ui.dialog.cancel` goes back unchanged. Setting `flattenerPreset` drops `flattener`. `useArtboards: false` opens it for one page of the visible art's bounds, as Export As with Use Artboards off does: the dialog has no Artboards section and its `__artBounds` field is true. `ui.dialog.confirm` writes `path` (else asks for one), returns `{path, bytes, warnings}` and opens the file when `viewAfterSaving` is set. With `useArtboards: false` it writes the page as `app.export` does and returns `{path, warnings}`, or `{background: true, status}` while Background Export writes it | +| `engine.execute` `ui.savePdfDialog` | `{path?, preset?, range?, …document.exportPdf options}` | opens the Save PDF dialog (`file.export.pdf` with no params opens it too). Its fields are the `document.exportPdf` options: set `compatibility` with `ui.dialog.set {field: "compatibility", value: "1.5"}`, a section with `{field: "compression", value: {…}}` (the options it leaves out keep the dialog's values; a value that isn't an object is an error), the artboards with `__allArtboards: false` and `range`, the visible section with `__section` (General, Compression, Marks and Bleeds, Output, Advanced, Security, Summary), and the bleed link with `__bleedLinked` (true gives every side the top value; any value other than true or false is an error; setting `bleed` turns the link on when its four sides are equal and off when they differ). In Advanced, Custom… beside Flattener preset (enabled when the file is flattened: PDF 1.3, PDF/X-1a, PDF/X-3) opens the `pdfFlattenerOptions` dialog over Save PDF on the flattener options the save would use; its fields are those options, with `clipComplexRegions`, `preserveAlpha` and `preserveOverprints` set by the writer and Overprint. Its `ui.dialog.confirm` sets `flattener` (the preset then shows [Custom]; options equal to the preset's leave it unset) and goes back to Save PDF, and `ui.dialog.cancel` goes back unchanged. Setting `flattenerPreset` drops `flattener`. `useArtboards: false` opens it for one page of the visible art's bounds, as Export As with Use Artboards off does: the dialog has no Artboards section and its `__artBounds` field is true. `ui.dialog.confirm` writes `path` (else asks for one), returns `{path, bytes, warnings}` and opens the file when `viewAfterSaving` is set. With `useArtboards: false` it writes the page as `app.export` does and returns `{path, warnings}`, or `{background: true, status}` while Background Export writes it | | `file.save` / `file.saveAs` / `file.saveCopy` / `file.saveAsTemplate` (via `engine.execute`) | `{path?, format?, options?, svg?}` | Save writes the document's own file in its own format (a document opened from or saved as SVG/PDF saves as that again; the result's `warnings` say what the format loses). With `path` the file is written at once (Save As or a Copy to an SVG path without SVG options first opens SVG Options, below). Without one (never saved, a converted older file, Save As, a Copy, a Template) the app shows a save panel with one file type per save format (`vectorcraft`, `template`, `pdf`, `svg`, `svgz`, `ai`; for a Template, `template` and `ait`), then the format's options: SVG opens the `svgOptions` dialog (below; returns `{"pending": "svgOptions", "path"}`), PDF the `savePdf` dialog (its `__save` field names the save command); `ui.dialog.confirm` finishes the save. A name typed in the panel without the file type's extension gets it, and a name the panel returns with the extension of a format the panel does not list has it replaced (in a native save, `card.png` and `card.ait` are saved as `card.vectorcraft`, and `notes.v2`, whose extension names no format, is saved as `notes.v2.vectorcraft`); when a file of that name exists, which the panel did not ask about, the save (and every export or other write through a save panel) answers `cancelled` and opens a `replaceFile` dialog (fields `message`, `detail`, `path`): `ui.dialog.confirm` writes that file, `ui.dialog.cancel` writes nothing. A save or export that writes other files beside that path (a file per artboard, linked images, image maps) checks them before it writes anything: when any of them exists, it writes nothing and opens a `replaceFiles` dialog (fields `message`, `detail` (each file's name when there are several), `files`, `__command`, `__params`; the reply is `{"pending": "replaceFiles"}`, or comes once a Background Save or Export ends): `ui.dialog.confirm` runs the save or export again and replaces them, `ui.dialog.cancel` writes nothing; a dialog open when a background job asks stays open, and the question follows it. A save does not ask about the files the document's last Save or Save As in this session wrote. On the web a `saveOptions` dialog (fields `path`, `format`) first names the file and picks the format. `file.formatOptions {format?}` reads the options a save would use. `file.revert` opens a `confirm` dialog (`{"pending": "confirm"}`); `ui.dialog.confirm` reloads the saved file in the same tab. Location refusals return `READ_ONLY_LOCATION: ` without a fallback panel for automation; see [Save location errors](#save-location-errors). | | SVG Options (`engine.execute` of `file.export.svg`, `file.saveAs`, `file.saveCopy`) | `{}` / `{path?, svg?: {…}}` | `file.export.svg` without params, and Save As or Save a Copy to an `.svg`/`.svgz` path without SVG options, open the `svgOptions` dialog (`ui.dialog.set` its fields: `styling`, `outlineText`, `images`, `objectIds`, `decimals`, `minify`, `responsive`, `fewerTspans`, `metadata`, `preserveEditing`, `useArtboards`, `allArtboards`, `range`, `showCode`, `profile` (`svg11`/`tiny12`), `encoding` (`utf8`/`utf16`/`latin1`), `embedFonts`; `ui.dialog.confirm` exports or saves and remembers the choices). The dialog's Show in Browser button (`file.export.svg.browser`) writes the SVG of the current choices for one page to a temporary folder and opens it in the default browser, leaving the dialog open; a request through `engine.execute` is refused because it opens another app. With `svg: {…}` (the `document.formats` SVG options) they run directly. `app.save {path?, svg?}` takes the same options; a document saved as SVG saves as SVG again with the same options | | `engine.execute` `file.place` | `{paths?}` / `{path \| name+dataBase64, …file.place params}` | with no file, picks files and opens the `place` dialog; with `paths`, opens it for them (fields `files`, `link`, `template`, `replace`; `__replace` says whether Replace applies, `__info` describes each file). `ui.dialog.confirm` places one file centered in the view (or in place of the selected object) and loads the place cursor with several (`file.place.queue`). In the desktop app the dialog reads its files off the UI thread: `__info` is empty until they are read, `ui.dialog.confirm` returns `{background: true, status}`, `ui.inspect` lists the files still being read in `placing`, and the file is placed (or the cursor loaded) once it is read. With a file, it runs `file.place` centered in the view, at once. Files dropped on the window with no document open open. On the web, files dropped on the canvas are placed at the drop point (linked; Shift embeds) and files dropped off it (the tab bar) open, as in Illustrator; desktop drops carry no pointer position, so documents (native, SVG, PDF, `.ai`, EPS, DXF, EMF/WMF) open as tabs of their own and pictures and text are placed in the middle of the view. Swatch libraries and color books (`.vcswatches`, `.gpl`, `.ase`, `.acb`), graphic style libraries (`.vcstyles`), Libraries panel files (`.vclibrary`), presets (`.vcflattener`, `.vcpdfpresets`, `.vcprintpresets`, `.vcperspective`, `.vcexportpresets`), plug-ins (`.wasm`) and shortcut sets (`.kys`, in Import Shortcut Set) open wherever they are dropped, as File › Open opens them. With the cursor loaded (`ui.inspect` → `tool: "place"`, `toolOptions: {count, current, name, names}`), `ui.pointer` clicks and drags place files (in the desktop app each file is read off the UI thread and placed once it is read, and `ui.inspect` lists it in `placing` until then) and `ui.key` ←/→/↑/↓ and Escape cycle and discard them | From a49d4f2036e46f90d03346ab5762c693618f32e0 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 00:42:10 -0800 Subject: [PATCH 026/151] Save PDF: a settings object set after a null one keeps the preset's options docs/control-protocol.md said every settings value that isn't an object is an error. A null is set as it is, and the save takes that section from the preset; the docs now say so. A settings object set after that section was null took the options it leaves out from the default settings, so setting only marks.weight turned off the preset's trim marks. They now come from Save PDF's preset, as the save takes them. The test covers both. --- crates/ui-egui/src/dialogs.rs | 2 +- crates/ui-egui/src/dialogs/save_pdf.rs | 32 +++++++++++++++----- crates/ui-egui/src/dialogs/save_pdf/tests.rs | 11 +++++++ docs/control-protocol.md | 2 +- 4 files changed, 37 insertions(+), 10 deletions(-) diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index ed805635bc..c074c2a9f9 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -749,7 +749,7 @@ pub(crate) fn field_set(app: &mut VectorcraftApp, field: &str, old: Option<&Valu return composite_fonts::field_set(d, field); } if let Some(d) = app.ui.dialog.as_mut().filter(|d| d.kind == save_pdf::KIND || d.kind == save_pdf::PRESET_KIND) { - return save_pdf::field_set(d, field, old); + return save_pdf::field_set(d, field, old, &app.session.prefs.pdf_presets); } if let Some(d) = app.ui.dialog.as_mut().filter(|d| d.kind == eps_options::KIND) { eps_options::field_set(d, field); diff --git a/crates/ui-egui/src/dialogs/save_pdf.rs b/crates/ui-egui/src/dialogs/save_pdf.rs index 75f9c7179f..74f08b2fae 100644 --- a/crates/ui-egui/src/dialogs/save_pdf.rs +++ b/crates/ui-egui/src/dialogs/save_pdf.rs @@ -22,8 +22,8 @@ use vectorcraft_doc::Unit; use vectorcraft_engine::cmd::fileio::{SaveMode, pdf}; use vectorcraft_engine::cmd::{FlattenOptions, FlattenerPreset}; use vectorcraft_pdf::{ - Changes, Choice, ColorConversion, Compatibility, Downsample, Encryption, ImageCodec, JpegQuality, MarkKind, MonoCodec, Overprint, PdfSettings, - Printing, ProfileInclusion, Standard, + Changes, Choice, ColorConversion, Compatibility, Downsample, Encryption, ImageCodec, JpegQuality, MarkKind, MonoCodec, Overprint, PdfPreset, + PdfSettings, Printing, ProfileInclusion, Standard, }; use super::{DialogSpec, form}; @@ -803,10 +803,11 @@ fn edit_bleed(d: &mut Dialog, side: usize, value: f64) { /// same values included, drops the link's state, so the link follows the values set. A flattener /// preset set there drops the Custom… options, as choosing it in the dropdown does. A settings /// object (`bleed`, `marks`, `compression`…) set there must be an object and sets only the options -/// it holds: the ones it leaves out keep the values the dialog had (`old`). -pub(super) fn field_set(d: &mut Dialog, field: &str, old: Option<&Value>) -> Result<(), String> { +/// it holds: the ones it leaves out keep the values the dialog had (`old`), or the values of the +/// Save PDF preset (built-in or `saved`) when the dialog had none. +pub(super) fn field_set(d: &mut Dialog, field: &str, old: Option<&Value>, saved: &[PdfPreset]) -> Result<(), String> { if DEFAULTS.get(field).is_some_and(Value::is_object) { - keep_unset_options(d, field, old)?; + keep_unset_options(d, field, old, saved)?; } match field { BLEED_LINKED => match d.fields.get(BLEED_LINKED).cloned() { @@ -829,18 +830,33 @@ pub(super) fn field_set(d: &mut Dialog, field: &str, old: Option<&Value>) -> Res } /// The settings object `field` that `ui.dialog.set` set, with the options it leaves out taken from -/// `old` (the default settings' when the dialog had none). A null is kept as it was set. -fn keep_unset_options(d: &mut Dialog, field: &str, old: Option<&Value>) -> Result<(), String> { +/// `old`. When the dialog had none (never set, or set to null), they come from Save PDF's preset, +/// as the save takes them, and from the default settings in the preset editor. A null is kept as +/// it was set. +fn keep_unset_options(d: &mut Dialog, field: &str, old: Option<&Value>, saved: &[PdfPreset]) -> Result<(), String> { + let preset = if d.kind == KIND { d.str("preset") } else { String::new() }; let Some(new) = d.fields.get_mut(field).filter(|v| !v.is_null()) else { return Ok(()) }; if !new.is_object() { return Err(format!("{field} must be an object of options, not {new}")); } - let mut merged = old.filter(|o| o.is_object()).or_else(|| DEFAULTS.get(field)).cloned().unwrap_or_default(); + let mut merged = match old.filter(|o| o.is_object()) { + Some(o) => o.clone(), + None => preset_section(&preset, field, saved).or_else(|| DEFAULTS.get(field).cloned()).unwrap_or_default(), + }; merge_options(&mut merged, new); *new = merged; Ok(()) } +/// The settings object `field` of the preset `name` (built-in or `saved`); None for no preset. +fn preset_section(name: &str, field: &str, saved: &[PdfPreset]) -> Option { + if name.is_empty() { + return None; + } + let settings = pdf::resolve("ui.savePdfDialog", &json!({ "preset": name }), saved).ok()?; + serde_json::to_value(settings).ok()?.get_mut(field).map(Value::take) +} + /// Set the options `over` holds on `base`, object by object. fn merge_options(base: &mut Value, over: &Value) { match (base, over) { diff --git a/crates/ui-egui/src/dialogs/save_pdf/tests.rs b/crates/ui-egui/src/dialogs/save_pdf/tests.rs index d59c2eea4b..b568c627d3 100644 --- a/crates/ui-egui/src/dialogs/save_pdf/tests.rs +++ b/crates/ui-egui/src/dialogs/save_pdf/tests.rs @@ -1070,6 +1070,17 @@ fn ui_dialog_set_keeps_the_options_a_settings_object_leaves_out() { assert!(r["error"].as_str().is_some_and(|e| e.contains("bleed must be an object of options")), "{bad}: {r}"); assert_eq!(dialog_json(&app), before, "{bad}"); } + + // A null settings object is set as it is: the save takes that section from the preset. + let r = dialog_set(&mut app, json!([{"field": "marks", "value": null}])); + assert_eq!(r["ok"], true, "{r}"); + let d = app.ui.dialog.as_ref().unwrap(); + assert!(d.fields.get("marks").is_some_and(Value::is_null) && params(d)["marks"].is_null(), "{:?}", d.fields.get("marks")); + // A settings object set after that takes the options it leaves out from the preset, as the save would. + let r = dialog_set(&mut app, json!([{"field": "marks", "value": {"weight": 0.25}}])); + assert_eq!(r["ok"], true, "{r}"); + let d = app.ui.dialog.as_ref().unwrap(); + assert_eq!((get(d, "marks.trim"), get(d, "marks.offset"), get(d, "marks.weight")), (&json!(true), &json!(9.0), &json!(0.25))); } /// A `ui.dialog.set` request whose later field is refused leaves the whole dialog as it was diff --git a/docs/control-protocol.md b/docs/control-protocol.md index 4df97a70b7..32d01b8f84 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -110,7 +110,7 @@ the two can still win that race. | `app.open` / `app.save` / `app.export` / `app.quit` | `{path, importer?, params?}` / `{path?}` / `{path?, format?, artboard?, range?, scale?, …}` | `app.open` reads every format `document.open` reads (see `document.formats`) and returns its result (`{index, title, format, warnings, …}`; `warnings` say what didn't come in as it was, such as an EPS shown as its preview image and why its PostScript couldn't be read), or null when a dialog asks first or a library loads. The status bar (`ui.inspect` → `ui.status`), after a line about the document's linked files when there is one (Missing linked files below), counts the `warnings` and names the first that says reading the file left something out (the notes that make Save ask before writing over it), else the first; with several, hovering it lists them in that order, as many as fit in the window (at most 30), then how many more. After `app.save`, and `app.export` with a `path`, the status bar counts the reply's `warnings` and names the first, and with several, hovering it lists them in the reply's order (a save's notes start with what the format loses). With `importer` (an importer plug-in's format id, `plugin.`) it runs `file.openWith`: the file opens with that importer, also when a built-in format reads its extension, with the importer's parameters `params` (their defaults when omitted; no dialog asks for them). Without `importer`, `params` go to the importer that opens the file, and a built-in format does not read them. `app.export` encodes through the engine's `document.export` (same options; the document keeps its path) and writes `path` through the host; without `path` it returns `{dataBase64, format, bytes}`, as headless mode does. It refuses a key that no format takes, and an unknown key inside a PDF or EPS option object, before it writes anything (`docs/mcp.md`, Parameter keys). It accepts a key that only another format takes and does not use it: the reply's `warnings` and the status bar name the key ("`quality` was not used: PDF files don't read it"). `app.save` refuses a key that no save format takes, beside the path or in `options`, the same way. `app.quit`, `file.close` and `file.closeAll` first open a `saveChanges` dialog for each modified document (they return `{"pending": "saveChanges"}`): `ui.dialog.confirm` saves, `ui.dialog.set {field: "discard", value: true}` then confirm discards, `ui.dialog.cancel` cancels the whole close or quit | | `app.export` with `useArtboards` | `{path, useArtboards: true, range? \| artboards?, …}` | Export As: PNG, JPEG and WebP write one file per chosen artboard (default all; SVG does so for a `range`), `-.`, and return `{path, files: [path…]}`; a PDF keeps them as pages of `path`. `useArtboards: false` covers the bounds of the visible art. The menu's Export As… is `file.exportAs`: the `exportAs` dialog (`format`, `useArtboards`, `all`, `range`), then a save dialog and the format's options: `pngOptions` / `jpgOptions` / `webpOptions`, `svgOptions`, or `savePdf` for a PDF | | `ui.dialog.*` on `gradientStop` | `{field: "color" \| "opacity" \| "location", value}` | double-clicking a stop on the Gradient tool's annotator opens its popover (fields `index`, `x`, `y`, `tab`); set `color` (hex), `opacity` or `location` (percentages) and `ui.dialog.confirm` to apply them to the selected stop. `gradient.selectStop {index}` picks the stop the annotator, the panels and Delete/←/→ (`ui.key`) act on | -| `engine.execute` `ui.savePdfDialog` | `{path?, preset?, range?, …document.exportPdf options}` | opens the Save PDF dialog (`file.export.pdf` with no params opens it too). Its fields are the `document.exportPdf` options: set `compatibility` with `ui.dialog.set {field: "compatibility", value: "1.5"}`, a section with `{field: "compression", value: {…}}` (the options it leaves out keep the dialog's values; a value that isn't an object is an error), the artboards with `__allArtboards: false` and `range`, the visible section with `__section` (General, Compression, Marks and Bleeds, Output, Advanced, Security, Summary), and the bleed link with `__bleedLinked` (true gives every side the top value; any value other than true or false is an error; setting `bleed` turns the link on when its four sides are equal and off when they differ). In Advanced, Custom… beside Flattener preset (enabled when the file is flattened: PDF 1.3, PDF/X-1a, PDF/X-3) opens the `pdfFlattenerOptions` dialog over Save PDF on the flattener options the save would use; its fields are those options, with `clipComplexRegions`, `preserveAlpha` and `preserveOverprints` set by the writer and Overprint. Its `ui.dialog.confirm` sets `flattener` (the preset then shows [Custom]; options equal to the preset's leave it unset) and goes back to Save PDF, and `ui.dialog.cancel` goes back unchanged. Setting `flattenerPreset` drops `flattener`. `useArtboards: false` opens it for one page of the visible art's bounds, as Export As with Use Artboards off does: the dialog has no Artboards section and its `__artBounds` field is true. `ui.dialog.confirm` writes `path` (else asks for one), returns `{path, bytes, warnings}` and opens the file when `viewAfterSaving` is set. With `useArtboards: false` it writes the page as `app.export` does and returns `{path, warnings}`, or `{background: true, status}` while Background Export writes it | +| `engine.execute` `ui.savePdfDialog` | `{path?, preset?, range?, …document.exportPdf options}` | opens the Save PDF dialog (`file.export.pdf` with no params opens it too). Its fields are the `document.exportPdf` options: set `compatibility` with `ui.dialog.set {field: "compatibility", value: "1.5"}`, a section with `{field: "compression", value: {…}}` (the options it leaves out keep the dialog's values; null unsets the section, and the save takes it from the preset; any other value that isn't an object is an error), the artboards with `__allArtboards: false` and `range`, the visible section with `__section` (General, Compression, Marks and Bleeds, Output, Advanced, Security, Summary), and the bleed link with `__bleedLinked` (true gives every side the top value; any value other than true or false is an error; setting `bleed` turns the link on when its four sides are equal and off when they differ). In Advanced, Custom… beside Flattener preset (enabled when the file is flattened: PDF 1.3, PDF/X-1a, PDF/X-3) opens the `pdfFlattenerOptions` dialog over Save PDF on the flattener options the save would use; its fields are those options, with `clipComplexRegions`, `preserveAlpha` and `preserveOverprints` set by the writer and Overprint. Its `ui.dialog.confirm` sets `flattener` (the preset then shows [Custom]; options equal to the preset's leave it unset) and goes back to Save PDF, and `ui.dialog.cancel` goes back unchanged. Setting `flattenerPreset` drops `flattener`. `useArtboards: false` opens it for one page of the visible art's bounds, as Export As with Use Artboards off does: the dialog has no Artboards section and its `__artBounds` field is true. `ui.dialog.confirm` writes `path` (else asks for one), returns `{path, bytes, warnings}` and opens the file when `viewAfterSaving` is set. With `useArtboards: false` it writes the page as `app.export` does and returns `{path, warnings}`, or `{background: true, status}` while Background Export writes it | | `file.save` / `file.saveAs` / `file.saveCopy` / `file.saveAsTemplate` (via `engine.execute`) | `{path?, format?, options?, svg?}` | Save writes the document's own file in its own format (a document opened from or saved as SVG/PDF saves as that again; the result's `warnings` say what the format loses). With `path` the file is written at once (Save As or a Copy to an SVG path without SVG options first opens SVG Options, below). Without one (never saved, a converted older file, Save As, a Copy, a Template) the app shows a save panel with one file type per save format (`vectorcraft`, `template`, `pdf`, `svg`, `svgz`, `ai`; for a Template, `template` and `ait`), then the format's options: SVG opens the `svgOptions` dialog (below; returns `{"pending": "svgOptions", "path"}`), PDF the `savePdf` dialog (its `__save` field names the save command); `ui.dialog.confirm` finishes the save. A name typed in the panel without the file type's extension gets it, and a name the panel returns with the extension of a format the panel does not list has it replaced (in a native save, `card.png` and `card.ait` are saved as `card.vectorcraft`, and `notes.v2`, whose extension names no format, is saved as `notes.v2.vectorcraft`); when a file of that name exists, which the panel did not ask about, the save (and every export or other write through a save panel) answers `cancelled` and opens a `replaceFile` dialog (fields `message`, `detail`, `path`): `ui.dialog.confirm` writes that file, `ui.dialog.cancel` writes nothing. A save or export that writes other files beside that path (a file per artboard, linked images, image maps) checks them before it writes anything: when any of them exists, it writes nothing and opens a `replaceFiles` dialog (fields `message`, `detail` (each file's name when there are several), `files`, `__command`, `__params`; the reply is `{"pending": "replaceFiles"}`, or comes once a Background Save or Export ends): `ui.dialog.confirm` runs the save or export again and replaces them, `ui.dialog.cancel` writes nothing; a dialog open when a background job asks stays open, and the question follows it. A save does not ask about the files the document's last Save or Save As in this session wrote. On the web a `saveOptions` dialog (fields `path`, `format`) first names the file and picks the format. `file.formatOptions {format?}` reads the options a save would use. `file.revert` opens a `confirm` dialog (`{"pending": "confirm"}`); `ui.dialog.confirm` reloads the saved file in the same tab. Location refusals return `READ_ONLY_LOCATION: ` without a fallback panel for automation; see [Save location errors](#save-location-errors). | | SVG Options (`engine.execute` of `file.export.svg`, `file.saveAs`, `file.saveCopy`) | `{}` / `{path?, svg?: {…}}` | `file.export.svg` without params, and Save As or Save a Copy to an `.svg`/`.svgz` path without SVG options, open the `svgOptions` dialog (`ui.dialog.set` its fields: `styling`, `outlineText`, `images`, `objectIds`, `decimals`, `minify`, `responsive`, `fewerTspans`, `metadata`, `preserveEditing`, `useArtboards`, `allArtboards`, `range`, `showCode`, `profile` (`svg11`/`tiny12`), `encoding` (`utf8`/`utf16`/`latin1`), `embedFonts`; `ui.dialog.confirm` exports or saves and remembers the choices). The dialog's Show in Browser button (`file.export.svg.browser`) writes the SVG of the current choices for one page to a temporary folder and opens it in the default browser, leaving the dialog open; a request through `engine.execute` is refused because it opens another app. With `svg: {…}` (the `document.formats` SVG options) they run directly. `app.save {path?, svg?}` takes the same options; a document saved as SVG saves as SVG again with the same options | | `engine.execute` `file.place` | `{paths?}` / `{path \| name+dataBase64, …file.place params}` | with no file, picks files and opens the `place` dialog; with `paths`, opens it for them (fields `files`, `link`, `template`, `replace`; `__replace` says whether Replace applies, `__info` describes each file). `ui.dialog.confirm` places one file centered in the view (or in place of the selected object) and loads the place cursor with several (`file.place.queue`). In the desktop app the dialog reads its files off the UI thread: `__info` is empty until they are read, `ui.dialog.confirm` returns `{background: true, status}`, `ui.inspect` lists the files still being read in `placing`, and the file is placed (or the cursor loaded) once it is read. With a file, it runs `file.place` centered in the view, at once. Files dropped on the window with no document open open. On the web, files dropped on the canvas are placed at the drop point (linked; Shift embeds) and files dropped off it (the tab bar) open, as in Illustrator; desktop drops carry no pointer position, so documents (native, SVG, PDF, `.ai`, EPS, DXF, EMF/WMF) open as tabs of their own and pictures and text are placed in the middle of the view. Swatch libraries and color books (`.vcswatches`, `.gpl`, `.ase`, `.acb`), graphic style libraries (`.vcstyles`), Libraries panel files (`.vclibrary`), presets (`.vcflattener`, `.vcpdfpresets`, `.vcprintpresets`, `.vcperspective`, `.vcexportpresets`), plug-ins (`.wasm`) and shortcut sets (`.kys`, in Import Shortcut Set) open wherever they are dropped, as File › Open opens them. With the cursor loaded (`ui.inspect` → `tool: "place"`, `toolOptions: {count, current, name, names}`), `ui.pointer` clicks and drags place files (in the desktop app each file is read off the UI thread and placed once it is read, and `ui.inspect` lists it in `placing` until then) and `ui.key` ←/→/↑/↓ and Escape cycle and discard them | From e29e8b936a86be641ac0a7fd659cf63da8789a48 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 01:08:58 -0800 Subject: [PATCH 027/151] Tests: Undo and Redo name an effect step as the Effect menu does The Undo/Redo menu test now applies Feather in French, where the plain row of the English label and the Effect menu's Feather differ, and expects the effect's name from i18n::effect_name. The check of a plain step runs in Japanese. Also spells "catalog" in the built_in_effect doc comment. --- crates/effects/src/catalog.rs | 2 +- crates/ui-egui/src/menus/tests.rs | 27 +++++++++++++++------------ 2 files changed, 16 insertions(+), 13 deletions(-) diff --git a/crates/effects/src/catalog.rs b/crates/effects/src/catalog.rs index e0a81abb40..9ef42d8105 100644 --- a/crates/effects/src/catalog.rs +++ b/crates/effects/src/catalog.rs @@ -875,7 +875,7 @@ pub(crate) fn catalog_index() -> &'static std::collections::HashMap<&'static str INDEX.get_or_init(|| effect_catalog().into_iter().map(|e| (e.id, e)).collect()) } -/// The id and menu label of built-in effect `id`, as the catalogue holds them (no plug-in +/// The id and menu label of built-in effect `id`, as the catalog holds them (no plug-in /// effects). pub fn built_in_effect(id: &str) -> Option<(&'static str, &'static str)> { catalog_index().get(id).map(|e| (e.id, e.label)) diff --git a/crates/ui-egui/src/menus/tests.rs b/crates/ui-egui/src/menus/tests.rs index fa94c19cd5..44d3b482bd 100644 --- a/crates/ui-egui/src/menus/tests.rs +++ b/crates/ui-egui/src/menus/tests.rs @@ -557,13 +557,14 @@ fn last_effect_dialog_and_view_toggles() { } } -/// Edit › Undo and Edit › Redo name the step in the UI language as the History panel lists it -/// (`panels::history::step_name`), including a step named after an effect whose catalog holds -/// only the effect's menu row with an ellipsis, as Japanese does for Feather. +/// Edit › Undo and Edit › Redo name the step in the UI language as the History panel lists it: a +/// step that applied an effect by the effect's name as the Effect menu shows it +/// (`i18n::effect_name`), even where the plain row of its English label holds another word, as +/// French does for Feather, and any other step by `panels::history::step_name` of its label. #[test] fn undo_and_redo_name_the_step_as_the_history_panel_does() { - let ja = crate::i18n::Lang::from_code("ja").expect("ja registered"); - crate::i18n::set_current(ja); + let fr = crate::i18n::Lang::from_code("fr").expect("fr registered"); + crate::i18n::set_current(fr); let mut app = app_with_a_rectangle(); app.run("effect.apply", json!({"effect": "stylize.feather"})).unwrap(); assert_eq!(app.session.active().unwrap().history.undo.last().map(|h| h.label.as_str()), Some("Feather")); @@ -574,14 +575,16 @@ fn undo_and_redo_name_the_step_as_the_history_panel_does() { _ => panic!("{id} is not a menu item"), } }; - let step = |template: &str, name: &str| { - let name = crate::panels::history::step_name(ja, name).unwrap_or_else(|| name.to_string()); - crate::i18n::fmt(crate::i18n::tr(ja, template), &[("name", &name)]) - }; - assert_eq!(shown(&app, "edit.undo"), step("Undo {name}", "Feather")); + let step = |lang, template: &str, name: &str| crate::i18n::fmt(crate::i18n::tr(lang, template), &[("name", name)]); + let feather = crate::i18n::effect_name(fr, "stylize.feather").expect("the Effect menu names Feather"); + assert_eq!(shown(&app, "edit.undo"), step(fr, "Undo {name}", &feather)); app.run("edit.undo", json!({})).unwrap(); - assert_eq!(shown(&app, "edit.redo"), step("Redo {name}", "Feather")); - assert_eq!(shown(&app, "edit.undo"), step("Undo {name}", "Rectangle"), "a step with a plain row"); + assert_eq!(shown(&app, "edit.redo"), step(fr, "Redo {name}", &feather)); + // Japanese names a rectangle in other words than English. + let ja = crate::i18n::Lang::from_code("ja").expect("ja registered"); + crate::i18n::set_current(ja); + let rectangle = crate::panels::history::step_name(ja, "Rectangle").unwrap_or_else(|| "Rectangle".to_string()); + assert_eq!(shown(&app, "edit.undo"), step(ja, "Undo {name}", &rectangle), "a step with a plain row"); crate::i18n::set_current(crate::i18n::Lang::EN); assert_eq!(shown(&app, "edit.redo"), "Redo Feather"); } From 79ff502412299631878352c3041eca44344edc85 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 01:42:15 -0800 Subject: [PATCH 028/151] Save PDF: an object set where a settings object held a null one keeps the preset's options After ui.dialog.set left a null object inside a settings object (for example compression.color), a later object set there took the options it leaves out from the default settings, so the dialog showed a ppi of 300 while Save PDF used the preset's. They now come from the matching object of Save PDF's preset, as the save takes them. The test covers it. --- crates/ui-egui/src/dialogs/save_pdf.rs | 23 ++++++++++++++------ crates/ui-egui/src/dialogs/save_pdf/tests.rs | 11 ++++++++++ 2 files changed, 27 insertions(+), 7 deletions(-) diff --git a/crates/ui-egui/src/dialogs/save_pdf.rs b/crates/ui-egui/src/dialogs/save_pdf.rs index 74f08b2fae..0f27a355bb 100644 --- a/crates/ui-egui/src/dialogs/save_pdf.rs +++ b/crates/ui-egui/src/dialogs/save_pdf.rs @@ -831,19 +831,21 @@ pub(super) fn field_set(d: &mut Dialog, field: &str, old: Option<&Value>, saved: /// The settings object `field` that `ui.dialog.set` set, with the options it leaves out taken from /// `old`. When the dialog had none (never set, or set to null), they come from Save PDF's preset, -/// as the save takes them, and from the default settings in the preset editor. A null is kept as -/// it was set. +/// as the save takes them, and from the default settings in the preset editor. The same holds for +/// an object set where `old` holds a null object (`compression.color`). A null is kept as it was +/// set. fn keep_unset_options(d: &mut Dialog, field: &str, old: Option<&Value>, saved: &[PdfPreset]) -> Result<(), String> { let preset = if d.kind == KIND { d.str("preset") } else { String::new() }; let Some(new) = d.fields.get_mut(field).filter(|v| !v.is_null()) else { return Ok(()) }; if !new.is_object() { return Err(format!("{field} must be an object of options, not {new}")); } + let section = preset_section(&preset, field, saved).or_else(|| DEFAULTS.get(field).cloned()).unwrap_or_default(); let mut merged = match old.filter(|o| o.is_object()) { Some(o) => o.clone(), - None => preset_section(&preset, field, saved).or_else(|| DEFAULTS.get(field).cloned()).unwrap_or_default(), + None => section.clone(), }; - merge_options(&mut merged, new); + merge_options(&mut merged, new, Some(§ion)); *new = merged; Ok(()) } @@ -857,12 +859,19 @@ fn preset_section(name: &str, field: &str, saved: &[PdfPreset]) -> Option serde_json::to_value(settings).ok()?.get_mut(field).map(Value::take) } -/// Set the options `over` holds on `base`, object by object. -fn merge_options(base: &mut Value, over: &Value) { +/// Set the options `over` holds on `base`, object by object. An object set where `base` has none +/// starts from the matching object of `preset`. +fn merge_options(base: &mut Value, over: &Value, preset: Option<&Value>) { + if base.is_null() + && over.is_object() + && let Some(p) = preset.filter(|p| p.is_object()) + { + *base = p.clone(); + } match (base, over) { (Value::Object(b), Value::Object(o)) => { for (k, v) in o { - merge_options(b.entry(k.as_str()).or_insert(Value::Null), v); + merge_options(b.entry(k.as_str()).or_insert(Value::Null), v, preset.and_then(|p| p.get(k))); } } (b, o) => *b = o.clone(), diff --git a/crates/ui-egui/src/dialogs/save_pdf/tests.rs b/crates/ui-egui/src/dialogs/save_pdf/tests.rs index b568c627d3..e4508ba5f9 100644 --- a/crates/ui-egui/src/dialogs/save_pdf/tests.rs +++ b/crates/ui-egui/src/dialogs/save_pdf/tests.rs @@ -1081,6 +1081,17 @@ fn ui_dialog_set_keeps_the_options_a_settings_object_leaves_out() { assert_eq!(r["ok"], true, "{r}"); let d = app.ui.dialog.as_ref().unwrap(); assert_eq!((get(d, "marks.trim"), get(d, "marks.offset"), get(d, "marks.weight")), (&json!(true), &json!(9.0), &json!(0.25))); + + // The same for a null object inside a settings object: an object set there later takes the + // options it leaves out from the preset's object. + app.run("pdf.preset.save", json!({"name": "Low", "compression": {"color": {"ppi": 150}}})).unwrap(); + app.run("ui.savePdfDialog", json!({"preset": "Low"})).unwrap(); + for value in [json!({"color": null}), json!({"color": {}})] { + let r = dialog_set(&mut app, json!([{"field": "compression", "value": value}])); + assert_eq!(r["ok"], true, "{r}"); + } + let d = app.ui.dialog.as_ref().unwrap(); + assert_eq!(get(d, "compression.color.ppi"), &json!(150.0), "{:?}", d.fields.get("compression")); } /// A `ui.dialog.set` request whose later field is refused leaves the whole dialog as it was From 458e42866373af2fb610a2881dca8cf207667a3f Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 20 Nov 2026 22:10:14 -0800 Subject: [PATCH 029/151] Dynamic Text: a leading change on area type with Block on moves its Line Gap Block sets each character's leading to its size plus the frame's Line Gap and fits the text again after every edit, so a leading set from the Character panel, the Properties panel, the Type tool's Alt+arrow steps, a character style, the Eyedropper or Text Tweaker was accepted and then overwritten. On area type with Block on, a leading change now sets the Line Gap to the new leading less the size of the first character changed, within -1,296 to 1,296 pt, in the same undo step, and every line spreads or tightens by the change. text.setStyle and text.setRangeStyle take keepLineGap, which Reset Panel sends, so a reset to Auto leading keeps the frame's Line Gap. Point type, type on a path and area type with Block off keep their own leading. --- crates/engine/src/cmd/addons/typetools.rs | 8 +- crates/engine/src/cmd/appearance.rs | 14 +- crates/engine/src/cmd/textedit.rs | 17 +- crates/engine/src/cmd/textstyles.rs | 25 ++- crates/engine/src/cmd/typecmd.rs | 40 +++- crates/engine/src/cmd/typecmd/block.rs | 80 ++++++- crates/engine/src/cmd/typecmd/block_tests.rs | 209 +++++++++++++++++++ crates/engine/src/cmd/typemenu.rs | 2 +- crates/ui-egui/src/panels/character.rs | 8 +- crates/ui-egui/src/panels/character/tests.rs | 112 ++++++++++ docs/mcp.md | 16 ++ docs/target-app-parity.md | 2 +- 12 files changed, 514 insertions(+), 19 deletions(-) diff --git a/crates/engine/src/cmd/addons/typetools.rs b/crates/engine/src/cmd/addons/typetools.rs index d0c5447c42..14a462d79f 100644 --- a/crates/engine/src/cmd/addons/typetools.rs +++ b/crates/engine/src/cmd/addons/typetools.rs @@ -20,7 +20,7 @@ use vectorcraft_text::edit; use super::super::menucmds::whole_or; use super::super::object::choice; use super::super::textedit::{CharChange, text_mut, text_ref, type_ranges}; -use super::super::typecmd::refresh_bounds; +use super::super::typecmd::{refresh_bounds, refresh_with_given_leading}; use super::super::typemenu::{bake_dynamic_text, text_ids}; use super::super::{CommandSpec, bad, cmd, has_selection, number_or, switch_or, targets}; use crate::{EngineError, Result, Session}; @@ -170,7 +170,11 @@ fn text_tweaker(s: &mut Session, p: &Value) -> Result { for (id, changes) in &plans { let t = text_mut(d, *id).ok_or(EngineError::NoNode(*id))?; t.runs = tweak(std::mem::take(&mut t.runs), changes); - refresh_bounds(t); + // With Block on, the first changed character's leading goes to the frame's line gap. + match changes.first().filter(|_| key == "leading") { + Some(&(at, _)) => refresh_with_given_leading(t, at), + None => refresh_bounds(t), + } } Ok(()) })?; diff --git a/crates/engine/src/cmd/appearance.rs b/crates/engine/src/cmd/appearance.rs index 3b23d62634..d1d6194639 100644 --- a/crates/engine/src/cmd/appearance.rs +++ b/crates/engine/src/cmd/appearance.rs @@ -2003,7 +2003,12 @@ fn copy_from(s: &mut Session, p: &Value) -> Result { if let Some((_, para)) = picked.text.as_ref().filter(|_| attrs.paragraph) { t.edit_paras(Some(t.paragraphs_in(start, end)), |p| *p = para.clone()); } - super::typecmd::refresh_bounds(t); + // With Block on, the copied leading goes to the frame's line gap. + if characters.contains_key(&id) && start < end { + super::typecmd::refresh_with_given_leading(t, start); + } else { + super::typecmd::refresh_bounds(t); + } } check_text_bounds(d)?; let labels = super::graph::capture_label_text(d, &whole, kept_text, kept_para)?; @@ -2265,7 +2270,12 @@ impl Picked { t.set_all_paras(para.clone()); } if text.is_some() && (a.character || a.paragraph) { - super::typecmd::refresh_bounds(t); + // With Block on, the copied leading goes to the frame's line gap. + if character.is_some() { + super::typecmd::refresh_with_given_leading(t, 0); + } else { + super::typecmd::refresh_bounds(t); + } } return; } diff --git a/crates/engine/src/cmd/textedit.rs b/crates/engine/src/cmd/textedit.rs index 0d75061bee..2d6661f5aa 100644 --- a/crates/engine/src/cmd/textedit.rs +++ b/crates/engine/src/cmd/textedit.rs @@ -40,7 +40,7 @@ pub fn specs() -> Vec { "Character", [], None, - "{id? (default: the one selected type object), start?: byte, end?: byte (default: all text), story?: bool = false (all the text of every frame of the threaded story `id` is a frame of, in one undo step; no `start` or `end`), font?, style?, size?: pt 0.1..1296 (outside it: an error), leading?: pt|\"auto\", tracking?, kerning?: 1/1000 em|\"auto\"|\"optical\" (the space after each character), kerningBefore?: 1/1000 em -1000..10000 (the space before a character that starts a line by itself: the first character of the text, of a paragraph or after a forced line break; no effect elsewhere; 0 by default), baselineShift?: pt, hScale?: %, vScale?: %, rotation?: deg counter-clockwise (0: upright), fill?: colour|\"none\", stroke?: colour|\"none\" (#rrggbbaa and #rgba are refused in both), keepModel?: bool (fill and stroke, as paint.setFill), strokeWidth?: pt, strokeOptions?: {weight?, cap?, join?, miterLimit?, align?, dash?, dashOffset?, alignDashes?} (as stroke.set: the character stroke), underline?, strikethrough?, allCaps?: bool, smallCaps?: bool, position?: \"normal\"|\"superscript\"|\"subscript\" (sizes from Document Setup), features?: [\"dlig\", \"-liga\", \"salt=2\", …] (swsh, ss01–ss20, salt, titl, pnum, lnum, sups, subs, numr, dnom and aalt take the font's alternate number as `tag=N`, N 0–65535: \"salt=2\" draws the second alternate of each glyph that has one, \"salt\" is \"salt=1\", \"-salt\" and \"salt=0\" are off; \"hkna\" is H or V Style, kana in the font's forms for the writing direction, shaped as `vkna` in vertical type, and \"ital\" is Roman Italics, half-width alphanumerics in the font's italic forms, both on or off only; the range is shaped with its word, so a letter's alternate keeps it joined to its neighbours), featureChanges?: [\"tnum\", \"-onum\", \"salt=2\", …] (OpenType features turned on, or with - off, on top of each character's own, a value replacing the feature's last one; its other features are kept), charAlign?: \"romanBaseline\"|\"emBoxTop\"|\"emBoxCenter\"|\"emBoxBottom\"|\"icfTop\"|\"icfBottom\", proportionalMetrics?: bool (full-width glyphs on the font's proportional widths: `palt` in horizontal type, `vpal` in vertical type), tateChuYoko?: bool (Character panel menu › Tate-chu-yoko, with Show East Asian Options: in vertical type those characters stand side by side across one em of the column; kept on the characters and ignored in horizontal type), tcyUpDown?, tcyLeftRight?: pt -1296..1296 (Character panel menu › Tate-chu-yoko Settings: in vertical type a block of tate-chu-yoko characters moves up by a positive Up/Down and down by a negative one, right by a positive Left/Right and left by a negative one, as one piece with the values of its first character; on a vertical path a positive Up/Down moves it toward the path's start and a positive Left/Right to the path's left; 0 by default; automatic digit blocks and horizontal type do not move; neither turns tateChuYoko on), warichu?: bool (Character panel menu › Warichu, with Show East Asian Options: the characters are set at warichuScale percent of their size and stacked on warichuLines lines inside their line, one above the other in horizontal type and side by side in vertical type, the first line above or to the right; a stretch of them is one block with the settings of its first character that stays whole on one line and may run past its end; type on a path sets them at their own size), warichuLines?: 1..6 (default 2), warichuGap?: pt 0..100 (the space between the lines, default 0), warichuScale?: % 10..100 (default 50), warichuAlign?: \"auto\"|\"left\"|\"center\"|\"right\"|\"justifyLeft\"|\"justifyCenter\"|\"justifyRight\"|\"justifyAll\" (Warichu Settings: how the lines line up along the block, which is as long as its longest line; the justify values spread every line but the last, which is set left, centered or right, or spread with justifyAll; auto, the default, sets them as justifyLeft; left and right are top and bottom in vertical type; none of them turns warichu on), akiLeft?, akiRight?: 1/1000 em 0..1000 (Character panel › Insert Aki Left and Right, with Show East Asian Options: space before and after each character in reading order, on its left and right in left-to-right type, on its right and left in right-to-left type, above and below it in vertical type; a ligature or a letter with its marks takes the values of its first character; line wrapping counts it, alignment keeps it at a line's ends and justification does not stretch or narrow it; 0 by default; a value that is not a number or is outside the range is refused, naming the key), tsume?: % 0..100 (Character panel › Tsume, with Show East Asian Options: the share of the blank space on each side of each character's ink, inside its own width, that is taken away, the glyph keeping its shape; 100 sets the ink edge to edge; a color glyph's ink is its color art or bitmap; a character without ink, such as a space, keeps its width; a ligature or a letter with its marks takes the value of its first character; tracking, kerning and Insert Aki are added after it, and justification keeps it; in vertical type an upright character is measured above and below its ink inside its cell down the column, a character lying on its side along its own width, and a tate-chu-yoko block's characters across the column, the block keeping its one em; 0 by default; a value that is not a number or is outside the range is refused), diacriticHorizontal?, diacriticVertical?: 1/1000 em -1000..1000 (Character panel › Adjust Horizontal and Vertical Diacritic Position, with Show Indic Options: the font's mark glyphs among the characters, those its GDEF table classes as marks such as Arabic harakat and Hebrew points, move right by a positive horizontal value and up by a positive vertical one, relative to their letters, in thousandths of the size; a harakat or Hebrew point styled apart from its letter takes its own values and stays attached to it, and another mark takes its letter's; letters and fonts without mark classes do not move; 0 by default; a value that is not a number or is outside the range is refused, naming the key), standardVerticalRoman?: bool (Character panel menu › Standard Vertical Roman Alignment, with Show East Asian Options: in vertical type those half-width characters, such as Latin letters and digits, stand upright one below the other instead of being rotated; spaces and tate-chu-yoko blocks are not changed; kept on the characters and ignored in horizontal type; off by default), noBreak?: bool (Character panel menu › No Break: these characters stay on one line, including across a space inside the run), kashidas?: bool (Character panel menu › Kashidas: selected characters allow insertion only when both joined neighbors have it on; on by default), charDirection?: \"default\"|\"leftToRight\"|\"rightToLeft\" (Character panel menu › Character Direction: the characters are set left to right or right to left inside their paragraph, as a Unicode bidi embedding; default: as the bidi algorithm sets them), digits?: \"default\"|\"arabic\"|\"hindi\"|\"farsi\"|\"devanagari\"|\"bengali\"|\"gurmukhi\"|\"gujarati\"|\"odia\"|\"tamil\"|\"telugu\"|\"kannada\"|\"malayalam\" (Character panel menu › Digits: the numeral system every digit is drawn in, whatever was typed: Western, Arabic-Indic (hindi), Eastern Arabic-Indic (farsi) or an Indic script's own digits), glyphForm?: \"traditional\"|\"expert\"|\"jis04\"|\"jis90\"|\"jis78\"|\"jis83\"|\"fullWidth\"|\"halfWidth\"|\"thirdWidth\"|\"quarterWidth\"|\"default\" (Glyphs panel menu, with Show East Asian Options: the characters are drawn in that form of the font, the OpenType feature trad, expt, jp04, jp90, jp78, jp83, fwid, hwid, twid or qwid, one form at a time; a character the font has no such glyph for keeps its own; \"default\", Revert To Default Forms, draws the font's default glyphs; a form other than \"default\" takes away the characters' glyph choice (text.setGlyphAlternate); with fullWidth, halfWidth, thirdWidth or quarterWidth, proportionalMetrics is kept but `palt` is not applied, and the font's pair kerning is turned off; another value is refused), fontHeightReference?: \"emBox\"|\"capHeight\"|\"xHeight\"|\"icfBox\" (Character panel › Set Font Height Reference: the height of the font that size measures, the em box by default; with a font that has no such height, or one outside 0.1 to 2 em, the em box), language?: name|tag (Character panel › Language: one of Document Setup's languages by name or BCP 47 tag, case-insensitive, such as \"Turkish\" or \"tr\"; the characters are shaped in it, so the font uses that language's forms (OpenType `locl`); saved as the tag, English: USA, the default, as none; new type takes the document's language), fontAxes?: {\"wght\": 650, …} (Character panel › Variable Font: the setting of each variation axis named, in the axis's units and clamped to its range; null: back to the style's own setting; other axes keep theirs; tags the font has no axis for are left out; a font or style change clears them; text.fontList {family, style} lists the axes), glyphAlternate?: null (takes away the glyph choice text.setGlyphAlternate made on the characters, in the same undo step as the other attributes; any other value is refused)} style a character range (size/leading/baselineShift are document points and hScale includes the object transform; runs are split at the range ends) → {id, runs, warning?: text (the font or style set isn't available: its type is drawn in the fallback font or the family's closest style)}", + "{id? (default: the one selected type object), start?: byte, end?: byte (default: all text), story?: bool = false (all the text of every frame of the threaded story `id` is a frame of, in one undo step; no `start` or `end`), font?, style?, size?: pt 0.1..1296 (outside it: an error), leading?: pt|\"auto\" (on area type with Dynamic Text (Block) on, a leading change sets the frame's line gap to the new leading less the size of the first character changed, within -1296..1296 pt, as text.setStyle), keepLineGap?: bool = false (as text.setStyle), tracking?, kerning?: 1/1000 em|\"auto\"|\"optical\" (the space after each character), kerningBefore?: 1/1000 em -1000..10000 (the space before a character that starts a line by itself: the first character of the text, of a paragraph or after a forced line break; no effect elsewhere; 0 by default), baselineShift?: pt, hScale?: %, vScale?: %, rotation?: deg counter-clockwise (0: upright), fill?: colour|\"none\", stroke?: colour|\"none\" (#rrggbbaa and #rgba are refused in both), keepModel?: bool (fill and stroke, as paint.setFill), strokeWidth?: pt, strokeOptions?: {weight?, cap?, join?, miterLimit?, align?, dash?, dashOffset?, alignDashes?} (as stroke.set: the character stroke), underline?, strikethrough?, allCaps?: bool, smallCaps?: bool, position?: \"normal\"|\"superscript\"|\"subscript\" (sizes from Document Setup), features?: [\"dlig\", \"-liga\", \"salt=2\", …] (swsh, ss01–ss20, salt, titl, pnum, lnum, sups, subs, numr, dnom and aalt take the font's alternate number as `tag=N`, N 0–65535: \"salt=2\" draws the second alternate of each glyph that has one, \"salt\" is \"salt=1\", \"-salt\" and \"salt=0\" are off; \"hkna\" is H or V Style, kana in the font's forms for the writing direction, shaped as `vkna` in vertical type, and \"ital\" is Roman Italics, half-width alphanumerics in the font's italic forms, both on or off only; the range is shaped with its word, so a letter's alternate keeps it joined to its neighbours), featureChanges?: [\"tnum\", \"-onum\", \"salt=2\", …] (OpenType features turned on, or with - off, on top of each character's own, a value replacing the feature's last one; its other features are kept), charAlign?: \"romanBaseline\"|\"emBoxTop\"|\"emBoxCenter\"|\"emBoxBottom\"|\"icfTop\"|\"icfBottom\", proportionalMetrics?: bool (full-width glyphs on the font's proportional widths: `palt` in horizontal type, `vpal` in vertical type), tateChuYoko?: bool (Character panel menu › Tate-chu-yoko, with Show East Asian Options: in vertical type those characters stand side by side across one em of the column; kept on the characters and ignored in horizontal type), tcyUpDown?, tcyLeftRight?: pt -1296..1296 (Character panel menu › Tate-chu-yoko Settings: in vertical type a block of tate-chu-yoko characters moves up by a positive Up/Down and down by a negative one, right by a positive Left/Right and left by a negative one, as one piece with the values of its first character; on a vertical path a positive Up/Down moves it toward the path's start and a positive Left/Right to the path's left; 0 by default; automatic digit blocks and horizontal type do not move; neither turns tateChuYoko on), warichu?: bool (Character panel menu › Warichu, with Show East Asian Options: the characters are set at warichuScale percent of their size and stacked on warichuLines lines inside their line, one above the other in horizontal type and side by side in vertical type, the first line above or to the right; a stretch of them is one block with the settings of its first character that stays whole on one line and may run past its end; type on a path sets them at their own size), warichuLines?: 1..6 (default 2), warichuGap?: pt 0..100 (the space between the lines, default 0), warichuScale?: % 10..100 (default 50), warichuAlign?: \"auto\"|\"left\"|\"center\"|\"right\"|\"justifyLeft\"|\"justifyCenter\"|\"justifyRight\"|\"justifyAll\" (Warichu Settings: how the lines line up along the block, which is as long as its longest line; the justify values spread every line but the last, which is set left, centered or right, or spread with justifyAll; auto, the default, sets them as justifyLeft; left and right are top and bottom in vertical type; none of them turns warichu on), akiLeft?, akiRight?: 1/1000 em 0..1000 (Character panel › Insert Aki Left and Right, with Show East Asian Options: space before and after each character in reading order, on its left and right in left-to-right type, on its right and left in right-to-left type, above and below it in vertical type; a ligature or a letter with its marks takes the values of its first character; line wrapping counts it, alignment keeps it at a line's ends and justification does not stretch or narrow it; 0 by default; a value that is not a number or is outside the range is refused, naming the key), tsume?: % 0..100 (Character panel › Tsume, with Show East Asian Options: the share of the blank space on each side of each character's ink, inside its own width, that is taken away, the glyph keeping its shape; 100 sets the ink edge to edge; a color glyph's ink is its color art or bitmap; a character without ink, such as a space, keeps its width; a ligature or a letter with its marks takes the value of its first character; tracking, kerning and Insert Aki are added after it, and justification keeps it; in vertical type an upright character is measured above and below its ink inside its cell down the column, a character lying on its side along its own width, and a tate-chu-yoko block's characters across the column, the block keeping its one em; 0 by default; a value that is not a number or is outside the range is refused), diacriticHorizontal?, diacriticVertical?: 1/1000 em -1000..1000 (Character panel › Adjust Horizontal and Vertical Diacritic Position, with Show Indic Options: the font's mark glyphs among the characters, those its GDEF table classes as marks such as Arabic harakat and Hebrew points, move right by a positive horizontal value and up by a positive vertical one, relative to their letters, in thousandths of the size; a harakat or Hebrew point styled apart from its letter takes its own values and stays attached to it, and another mark takes its letter's; letters and fonts without mark classes do not move; 0 by default; a value that is not a number or is outside the range is refused, naming the key), standardVerticalRoman?: bool (Character panel menu › Standard Vertical Roman Alignment, with Show East Asian Options: in vertical type those half-width characters, such as Latin letters and digits, stand upright one below the other instead of being rotated; spaces and tate-chu-yoko blocks are not changed; kept on the characters and ignored in horizontal type; off by default), noBreak?: bool (Character panel menu › No Break: these characters stay on one line, including across a space inside the run), kashidas?: bool (Character panel menu › Kashidas: selected characters allow insertion only when both joined neighbors have it on; on by default), charDirection?: \"default\"|\"leftToRight\"|\"rightToLeft\" (Character panel menu › Character Direction: the characters are set left to right or right to left inside their paragraph, as a Unicode bidi embedding; default: as the bidi algorithm sets them), digits?: \"default\"|\"arabic\"|\"hindi\"|\"farsi\"|\"devanagari\"|\"bengali\"|\"gurmukhi\"|\"gujarati\"|\"odia\"|\"tamil\"|\"telugu\"|\"kannada\"|\"malayalam\" (Character panel menu › Digits: the numeral system every digit is drawn in, whatever was typed: Western, Arabic-Indic (hindi), Eastern Arabic-Indic (farsi) or an Indic script's own digits), glyphForm?: \"traditional\"|\"expert\"|\"jis04\"|\"jis90\"|\"jis78\"|\"jis83\"|\"fullWidth\"|\"halfWidth\"|\"thirdWidth\"|\"quarterWidth\"|\"default\" (Glyphs panel menu, with Show East Asian Options: the characters are drawn in that form of the font, the OpenType feature trad, expt, jp04, jp90, jp78, jp83, fwid, hwid, twid or qwid, one form at a time; a character the font has no such glyph for keeps its own; \"default\", Revert To Default Forms, draws the font's default glyphs; a form other than \"default\" takes away the characters' glyph choice (text.setGlyphAlternate); with fullWidth, halfWidth, thirdWidth or quarterWidth, proportionalMetrics is kept but `palt` is not applied, and the font's pair kerning is turned off; another value is refused), fontHeightReference?: \"emBox\"|\"capHeight\"|\"xHeight\"|\"icfBox\" (Character panel › Set Font Height Reference: the height of the font that size measures, the em box by default; with a font that has no such height, or one outside 0.1 to 2 em, the em box), language?: name|tag (Character panel › Language: one of Document Setup's languages by name or BCP 47 tag, case-insensitive, such as \"Turkish\" or \"tr\"; the characters are shaped in it, so the font uses that language's forms (OpenType `locl`); saved as the tag, English: USA, the default, as none; new type takes the document's language), fontAxes?: {\"wght\": 650, …} (Character panel › Variable Font: the setting of each variation axis named, in the axis's units and clamped to its range; null: back to the style's own setting; other axes keep theirs; tags the font has no axis for are left out; a font or style change clears them; text.fontList {family, style} lists the axes), glyphAlternate?: null (takes away the glyph choice text.setGlyphAlternate made on the characters, in the same undo step as the other attributes; any other value is refused)} style a character range (size/leading/baselineShift are document points and hScale includes the object transform; runs are split at the range ends) → {id, runs, warning?: text (the font or style set isn't available: its type is drawn in the fallback font or the family's closest style)}", has_doc, set_range_style ), @@ -103,7 +103,7 @@ pub fn specs() -> Vec { "Step Type", [], None, - "{attribute: \"size\"|\"leading\"|\"tracking\"|\"kerning\"|\"baselineShift\", by?: steps (1; negative steps down), id?, start?: byte, end?: byte, ids?: [id…] (instead of id)} step type by the Preferences › Type increments (size and leading: typeSizeIncrement, pt; tracking and kerning: trackingIncrement, 1/1000 em; baseline shift: baselineShiftIncrement, pt), what the Type tool's Alt+arrows do (Cmd/Ctrl too: five steps; horizontal: ←/→ kerning at the caret or tracking of the selection, ↑/↓ leading, Shift+↑/↓ baseline shift; vertical: ↓/↑ with or without Shift kerning or tracking, ←/→ leading, Shift+→/← baseline shift; mixed selected text objects use the horizontal mapping). The range of `id`, else the type objects in `ids`, else the text the Type tool has selected (at a caret: kerning steps the space after the character before it, or at the start of a line (of the text, a paragraph, or after a forced line break) the space before the character after it (kerningBefore, as text.setRangeStyle), and nothing at an empty line's start; leading its paragraph), else every selected type object → {ids}", + "{attribute: \"size\"|\"leading\"|\"tracking\"|\"kerning\"|\"baselineShift\", by?: steps (1; negative steps down), id?, start?: byte, end?: byte, ids?: [id…] (instead of id)} step type by the Preferences › Type increments (size and leading: typeSizeIncrement, pt; tracking and kerning: trackingIncrement, 1/1000 em; baseline shift: baselineShiftIncrement, pt), what the Type tool's Alt+arrows do (Cmd/Ctrl too: five steps; horizontal: ←/→ kerning at the caret or tracking of the selection, ↑/↓ leading, Shift+↑/↓ baseline shift; vertical: ↓/↑ with or without Shift kerning or tracking, ←/→ leading, Shift+→/← baseline shift; mixed selected text objects use the horizontal mapping). The range of `id`, else the type objects in `ids`, else the text the Type tool has selected (at a caret: kerning steps the space after the character before it, or at the start of a line (of the text, a paragraph, or after a forced line break) the space before the character after it (kerningBefore, as text.setRangeStyle), and nothing at an empty line's start; leading its paragraph), else every selected type object. On area type with Dynamic Text (Block) on, a leading change sets the frame's line gap to the new leading less the size of the first character changed, within -1296..1296 pt, as text.setStyle → {ids}", has_doc, type_step ), @@ -1207,6 +1207,7 @@ fn set_range_style(s: &mut Session, p: &Value) -> Result { }, }; let story = switch_or(p, "story", false, C)?; + let keep_line_gap = switch_or(p, "keepLineGap", false, C)?; if story && ["start", "end"].iter().any(|k| p.get(*k).is_some_and(|v| !v.is_null())) { return Err(bad(C, "`story` styles the whole story: give no `start` or `end`")); } @@ -1250,7 +1251,11 @@ fn set_range_style(s: &mut Session, p: &Value) -> Result { let styled = if a == b { t.runs.clone() } else { unprotected_runs(&t.runs, a, b, &kept) }; set.extend(styled.iter().flat_map(super::fonts::run_fonts)); } - refresh_bounds(t); + // With Block on, the leading goes to the frame's line gap. + match change.leading.filter(|_| !keep_line_gap) { + Some(l) => super::typecmd::refresh_with_leading(t, a, l), + None => refresh_bounds(t), + } n = if *f == id { t.runs.len() } else { n }; } Ok(n) @@ -2061,7 +2066,11 @@ fn type_step(s: &mut Session, p: &Value) -> Result { } } edit::replace_range_styled(&mut t.runs, a, b, &runs); - refresh_bounds(t); + // With Block on, the step goes to the frame's line gap. + match runs.first().filter(|_| matches!(step, Step::Leading)) { + Some(first) => super::typecmd::refresh_with_leading(t, a, first.style.leading), + None => refresh_bounds(t), + } } Ok(()) })?; diff --git a/crates/engine/src/cmd/textstyles.rs b/crates/engine/src/cmd/textstyles.rs index cde1456589..a804984ff6 100644 --- a/crates/engine/src/cmd/textstyles.rs +++ b/crates/engine/src/cmd/textstyles.rs @@ -500,13 +500,21 @@ fn update_users(d: &mut Document, kind: Kind, name: &str, old: &Map { + let mut off = 0; for r in &mut t.runs { if r.style.style_name == target { + let was = r.style.leading; r.style = font_change(&r.style, restyle(&r.style, char_attrs, old, new, &base), new); changed = true; + if r.style.leading != was && leading_at.is_none() { + leading_at = Some(off); + } } + off += r.text.len(); } } Kind::Para => { @@ -519,7 +527,11 @@ fn update_users(d: &mut Document, kind: Kind, name: &str, old: &Map super::typecmd::refresh_with_given_leading(t, at), + None => refresh_bounds(t), + } } Ok(()) }) @@ -971,6 +983,8 @@ fn apply(s: &mut Session, p: &Value, kind: Kind) -> Result { let attrs = kind.attrs(d, &name).ok_or_else(|| bad(&c, format!("no style `{name}`")))?; let normal = kind.attrs(d, kind.normal()).unwrap_or_default(); let clear = bool_or(p, "clearOverrides", false); + // The style sets a leading, or clearing overrides gives the text Normal's. + let sets_leading = kind == Kind::Char && (attrs.contains_key("leading") || (clear && normal.contains_key("leading"))); let style_name = (name != kind.normal()).then(|| name.clone()); // A Type tool range or whole text objects. let text_range = super::typecmd::TextRange::parse(p, &c)?; @@ -997,6 +1011,8 @@ fn apply(s: &mut Session, p: &Value, kind: Kind) -> Result { s.edit_named("Apply {name}", &name, name == kind.normal(), |d, _| { for id in &ids { let Some(t) = text_mut(d, *id) else { continue }; + // The first character given the style's leading. + let mut leading_at = None; match kind { Kind::Char => { let len = vectorcraft_text::edit::runs_len(&t.runs); @@ -1017,6 +1033,7 @@ fn apply(s: &mut Session, p: &Value, kind: Kind) -> Result { if let Some(e) = err { return Err(e); } + leading_at = (sets_leading && (a != b || len == 0)).then_some(a.min(b)); } Kind::Para => { let mut v = t.paragraph_styles(); @@ -1030,7 +1047,11 @@ fn apply(s: &mut Session, p: &Value, kind: Kind) -> Result { t.set_paragraph_styles(v); } } - refresh_bounds(t); + // With Block on, a leading the style sets goes to the frame's line gap. + match leading_at { + Some(at) => super::typecmd::refresh_with_given_leading(t, at), + None => refresh_bounds(t), + } } Ok(()) })?; diff --git a/crates/engine/src/cmd/typecmd.rs b/crates/engine/src/cmd/typecmd.rs index 185baf734f..ea5a416165 100644 --- a/crates/engine/src/cmd/typecmd.rs +++ b/crates/engine/src/cmd/typecmd.rs @@ -95,7 +95,7 @@ pub fn specs() -> Vec { "Area Type Options…", ["Type"], None, - "{ids?|id?, width?: pt, height?: pt, rows?, columns?, gutter?: pt (between rows and columns), rowGutter?: pt|null (between rows when it differs from gutter, which is then between columns; gutter given alone sets both; the reply gives the rows' gutter either way), inset?: pt, firstBaseline?: ascent|capHeight|xHeight|leading|emBoxHeight|fixed (emBoxHeight: the top of the first line's ideographic em box, the largest on the line, touches the top of the type area inside the inset), firstBaselineMin?: pt (the least distance from that top to the first baseline; with fixed, the distance), verticalAlign?: top|center|bottom|justify, flow?: columns|rows (Text Flow: down each column's rows, then across, the default; or across each row's columns, then down), fit?: none|autoHeight|shrinkText|block, fitMinPercent?: 10..100, wordGap?: % 0..1000, lineGap?: pt -1296..1296, …the keys of its own reply (it can be passed back; the values it only reports are ignored)} set the selected area type's options (each frame takes the options given over its own and keeps the rest; fit resolves against each frame's own; options that change nothing add no undo step); width and height size the type area from its top-left corner, along the type's own axes, and the text reflows at its size (with fit autoHeight, Auto Size, the frame's height follows the text after every edit and height is ignored; setting the height by hand turns it off); fit shrinkText scales overflowing text down (size, leading, baseline shift) by the largest factor down to fitMinPercent % (default 50) that makes it fit; fit block is Dynamic Text's Block, as type.dynamicText sets it (in place of Auto Size and Shrink Text to Fit; threaded frames are refused; another fit turns it off, keeping the sizes it wrote), and wordGap and lineGap set its gaps (kept while Block is off; out of range is an error) (none given: query) → the first object's options, plus wordGap and lineGap, overflow (the text doesn't fit its frame) and fitScale (Shrink Text's factor, 1 unshrunk)", + "{ids?|id?, width?: pt, height?: pt, rows?, columns?, gutter?: pt (between rows and columns), rowGutter?: pt|null (between rows when it differs from gutter, which is then between columns; gutter given alone sets both; the reply gives the rows' gutter either way), inset?: pt, firstBaseline?: ascent|capHeight|xHeight|leading|emBoxHeight|fixed (emBoxHeight: the top of the first line's ideographic em box, the largest on the line, touches the top of the type area inside the inset), firstBaselineMin?: pt (the least distance from that top to the first baseline; with fixed, the distance), verticalAlign?: top|center|bottom|justify, flow?: columns|rows (Text Flow: down each column's rows, then across, the default; or across each row's columns, then down), fit?: none|autoHeight|shrinkText|block, fitMinPercent?: 10..100, wordGap?: % 0..1000, lineGap?: pt -1296..1296, …the keys of its own reply (it can be passed back; the values it only reports are ignored)} set the selected area type's options (each frame takes the options given over its own and keeps the rest; fit resolves against each frame's own; options that change nothing add no undo step); width and height size the type area from its top-left corner, along the type's own axes, and the text reflows at its size (with fit autoHeight, Auto Size, the frame's height follows the text after every edit and height is ignored; setting the height by hand turns it off); fit shrinkText scales overflowing text down (size, leading, baseline shift) by the largest factor down to fitMinPercent % (default 50) that makes it fit; fit block is Dynamic Text's Block, as type.dynamicText sets it (in place of Auto Size and Shrink Text to Fit; threaded frames are refused; another fit turns it off, keeping the sizes it wrote), and wordGap and lineGap set its gaps (kept while Block is off; out of range is an error; a leading change on the text also sets lineGap, as type.dynamicText says) (none given: query) → the first object's options, plus wordGap and lineGap, overflow (the text doesn't fit its frame) and fitScale (Shrink Text's factor, 1 unshrunk)", has_selection, area_options ), @@ -140,7 +140,7 @@ pub fn specs() -> Vec { "Character", [], None, - "{ids?|id?, font?, style? (font alone: the style is kept when the new family has it, else its closest), size?: pt 0.1..1296 (outside it: an error), leading?: pt|\"auto\", tracking?: 1/1000 em, justify?: \"auto\" (the start of each paragraph's direction)|\"left\"|\"center\"|\"right\"|\"justifyAll\", fill?: colour|\"none\", stroke?: colour|\"none\" (characters without a stroke weight get 1 pt; #rrggbbaa and #rgba are refused in both), keepModel?: bool (fill and stroke, as paint.setFill), strokeWidth?: pt (the character stroke's weight, in document points as stroke.set), features?: [\"dlig\", \"-liga\", \"salt=2\", …] OpenType (swsh, ss01–ss20, salt, titl, pnum, lnum, sups, subs, numr, dnom and aalt take the font's alternate number as `tag=N`, N 0–65535: \"salt=2\" draws the second alternate of each glyph that has one, \"salt\" is \"salt=1\", \"-salt\" and \"salt=0\" are off; \"hkna\" is H or V Style, kana in the font's forms for the writing direction, shaped as `vkna` in vertical type, and \"ital\" is Roman Italics, half-width alphanumerics in the font's italic forms, both on or off only), featureChanges?: [\"tnum\", \"-onum\", \"salt=2\", …] (OpenType features turned on, or with - off, on top of each character's own, a value replacing the feature's last one; its other features are kept), start?: byte, end?: byte} (size/leading are document points after object scaling; with a range: the character attributes style that range and justify the paragraphs it touches; without: all the text; no undo step when no character, paragraph or graph label style changes) → {ids, overflow?: [id…] (area type and type on a path whose text no longer fits; left out when all fits), warning?: text (the font or style set isn't available: its type is drawn in the fallback font or the family's closest style)}", + "{ids?|id?, font?, style? (font alone: the style is kept when the new family has it, else its closest), size?: pt 0.1..1296 (outside it: an error), leading?: pt|\"auto\", keepLineGap?: bool = false (true: Dynamic Text (Block) keeps the frame's line gap, as Reset Panel does), tracking?: 1/1000 em, justify?: \"auto\" (the start of each paragraph's direction)|\"left\"|\"center\"|\"right\"|\"justifyAll\", fill?: colour|\"none\", stroke?: colour|\"none\" (characters without a stroke weight get 1 pt; #rrggbbaa and #rgba are refused in both), keepModel?: bool (fill and stroke, as paint.setFill), strokeWidth?: pt (the character stroke's weight, in document points as stroke.set), features?: [\"dlig\", \"-liga\", \"salt=2\", …] OpenType (swsh, ss01–ss20, salt, titl, pnum, lnum, sups, subs, numr, dnom and aalt take the font's alternate number as `tag=N`, N 0–65535: \"salt=2\" draws the second alternate of each glyph that has one, \"salt\" is \"salt=1\", \"-salt\" and \"salt=0\" are off; \"hkna\" is H or V Style, kana in the font's forms for the writing direction, shaped as `vkna` in vertical type, and \"ital\" is Roman Italics, half-width alphanumerics in the font's italic forms, both on or off only), featureChanges?: [\"tnum\", \"-onum\", \"salt=2\", …] (OpenType features turned on, or with - off, on top of each character's own, a value replacing the feature's last one; its other features are kept), start?: byte, end?: byte} (size/leading are document points after object scaling; on area type with Dynamic Text (Block) on, a leading change sets the frame's line gap (text.areaOptions lineGap) to the new leading less the size of the first character changed, within -1296..1296 pt, so every line spreads or tightens by the change, unless keepLineGap is true; with a range: the character attributes style that range and justify the paragraphs it touches; without: all the text; no undo step when no character, paragraph or graph label style changes) → {ids, overflow?: [id…] (area type and type on a path whose text no longer fits; left out when all fits), warning?: text (the font or style set isn't available: its type is drawn in the fallback font or the family's closest style)}", has_doc, set_style ), @@ -335,6 +335,11 @@ pub(crate) fn refresh_bounds(t: &mut TextObject) { // Edits that changed the paragraph count keep one paragraph style per paragraph. t.normalize_paras(); block::block_fit(t); + refresh_fitted(t); +} + +/// The part of [`refresh_bounds`] after Block has fitted the lines. +fn refresh_fitted(t: &mut TextObject) { auto_height(t); let lay = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), t); t.cached_bounds = Some(lay.bounds); @@ -342,6 +347,27 @@ pub(crate) fn refresh_bounds(t: &mut TextObject) { t.cached_ink = Some((lay.bounds, vectorcraft_render::effects::preview::laid_out_ink(&lay, t))); } +/// [`refresh_bounds`] after a change that set the leading of the character at `at` to `leading` +/// (in text space; None: Auto): on area type with Block on the change goes to the frame's line gap +/// ([`block::leading_to_line_gap`]), and the lines are fitted again only when the gap changed. +pub(crate) fn refresh_with_leading(t: &mut TextObject, at: usize, leading: Option) { + if block::leading_to_line_gap(t, at, leading) { + refresh_fitted(t); + } else { + refresh_bounds(t); + } +} + +/// [`refresh_with_leading`] with the leading the character at `at` was just given (a character +/// style, the Eyedropper, Text Tweaker). +pub(crate) fn refresh_with_given_leading(t: &mut TextObject, at: usize) { + if block::given_leading_to_line_gap(t, at) { + refresh_fitted(t); + } else { + refresh_bounds(t); + } +} + /// [`refresh_bounds`] for a document that is opening: the first frame takes the layout /// ([`vectorcraft_text::take_kept_layout`]) instead of laying the object out again. pub(crate) fn refresh_bounds_for_first_frame(t: &mut TextObject) { @@ -955,6 +981,7 @@ fn set_style(s: &mut Session, p: &Value) -> Result { { return Err(bad(C, "nothing to change")); } + let keep_line_gap = switch_or(p, "keepLineGap", false, C)?; let range = TextRange::parse(p, C)?; let ids = text_targets(s, p, C)?; let protect = s.prefs.missing_glyph_protection && (font.is_some() || style.is_some()); @@ -1032,7 +1059,14 @@ fn set_style(s: &mut Session, p: &Value) -> Result { let span = para_span(range, t); t.edit_paras(span, |pa| pa.justify = j); } - refresh_bounds(t); + // With Block on, the leading goes to the frame's line gap; an empty range styles nothing. + let changed = leading + .filter(|_| !keep_line_gap) + .and_then(|l| range.map_or(Some(0), |r| Some(r.bytes(t)).filter(|(a, b)| a < b).map(|(a, _)| a)).map(|at| (at, l))); + match changed { + Some((at, l)) => refresh_with_leading(t, at, l), + None => refresh_bounds(t), + } } // Graph labels keep a change made to all of their text through the graph being drawn again (sizes as given, // not in a scaled label's own units). diff --git a/crates/engine/src/cmd/typecmd/block.rs b/crates/engine/src/cmd/typecmd/block.rs index ef14a57558..8a567f127c 100644 --- a/crates/engine/src/cmd/typecmd/block.rs +++ b/crates/engine/src/cmd/typecmd/block.rs @@ -2,7 +2,7 @@ //! typed is set to the frame's width by changing its font size, after every edit //! ([`super::refresh_bounds`]). -use vectorcraft_doc::{TextKind, TextObject, TextRun}; +use vectorcraft_doc::{CharStyle, TextKind, TextObject, TextRun}; /// The font size range a line's first character is fitted within, in document points (the /// Character panel's). @@ -56,6 +56,19 @@ pub(crate) fn size_at(runs: &[TextRun], byte: usize) -> f64 { vectorcraft_text::edit::style_at(runs, byte).size } +/// The run that holds the character at `byte` (not the one before it), else the last run. +fn run_at(runs: &[TextRun], byte: usize) -> Option<&TextRun> { + let mut off = 0; + for r in runs { + let end = off + r.text.len(); + if (off..end).contains(&byte) { + return Some(r); + } + off = end; + } + runs.last() +} + /// The stored size of each line's first character, in one pass over the runs. fn first_sizes(runs: &[TextRun], lines: &[TypedLine]) -> Vec { let mut out = Vec::with_capacity(lines.len()); @@ -122,6 +135,71 @@ pub(crate) fn needed_room(t: &TextObject) -> Option<(f64, usize, usize)> { .reduce(|a, b| if b.0 > a.0 { b } else { a }) } +/// Whether every character's leading is the one Block gives it: its size plus the frame's line +/// gap (in text space, at least the least size), as [`block_fit`] sets it. +fn block_leadings(t: &TextObject, points: f64) -> bool { + let gap = t.area.block_gaps().1 / points; + let min_leading = SIZES.0 / points; + t.runs.iter().all(|r| r.style.leading == Some((r.style.size + gap).max(min_leading))) +} + +/// A leading change on area type with Block on ([`TextObject::dynamic_text`]), called after the +/// change is applied to the characters: Block sets each character's leading to its size plus the +/// frame's line gap, so the change goes to the line gap instead. The lines are fitted, so the +/// character at `at` has the size Block gives it (a size set by the same change included); the gap +/// is then the leading `leading` gives that character (in text space; None: Auto) less its size, in +/// document points and kept within [`vectorcraft_doc::AreaOptions::LINE_GAP`]. That moves the gap +/// by the change to the character's leading, so every line spreads or tightens by the same amount. +/// A new gap moves the lines, which in a shaped frame changes the room each one has and so the size +/// Block gives the character, so the lines are fitted again and the gap worked out again from the +/// new size, at most [`BLOCK_PASSES`] times. True when the lines are fitted for the final gap, so the +/// caller lays the text out without fitting it again. Point type, type on a path and area type with +/// Block off are left as they are. +pub(crate) fn leading_to_line_gap(t: &mut TextObject, at: usize, leading: Option) -> bool { + if !t.dynamic_text || !matches!(t.kind, TextKind::Area { .. }) { + return false; + } + let Some(points) = t.style_scale().map(|s| s.points).filter(|p| p.is_finite() && *p > 1e-12) else { return false }; + t.normalize_paras(); + let para = t.plain_text().get(..at).map_or(0, |s| s.bytes().filter(|&c| c == b'\n').count()); + for _ in 0..BLOCK_PASSES { + block_fit(t); + // A frame Block could not fit leaves the characters as they were. + if !block_leadings(t, points) { + return false; + } + let Some(run) = run_at(&t.runs, at) else { return true }; + let size = run.style.size; + let new = match leading { + Some(l) => l, + None => { + // Auto leading as the layout sets it: the paragraph's Auto Leading share of the em size + // the font height reference gives the character. An inline graphic keeps its size. + let em = if run.inline.is_some() { size } else { vectorcraft_text::FontDb::global().em_size(&run.style, t.vertical) }; + t.para_at(para).effective_leading(&CharStyle { size: em, leading: None, ..run.style.clone() }) + } + }; + let gap = (new - size) * points; + if !gap.is_finite() { + return true; + } + let (lo, hi) = vectorcraft_doc::AreaOptions::LINE_GAP; + let next = gap.clamp(lo, hi); + if (next - t.area.line_gap).abs() <= 1e-9 { + return true; + } + t.area.line_gap = next; + } + false +} + +/// [`leading_to_line_gap`] with the leading the character at `at` was just given (a character +/// style, the Eyedropper, Text Tweaker), read before Block sets it again. +pub(crate) fn given_leading_to_line_gap(t: &mut TextObject, at: usize) -> bool { + let Some(leading) = run_at(&t.runs, at).map(|r| r.style.leading) else { return false }; + leading_to_line_gap(t, at, leading) +} + /// The size a line set at `size` points and `width` wide takes to fill `avail`, its width growing /// by `slope` a point of size (`width / size` when the whole line follows its size): rounded down /// to tenths and kept within [`SIZES`]. A line that fits and would not fit a tenth larger keeps its diff --git a/crates/engine/src/cmd/typecmd/block_tests.rs b/crates/engine/src/cmd/typecmd/block_tests.rs index 0354a630b3..911f5abfd1 100644 --- a/crates/engine/src/cmd/typecmd/block_tests.rs +++ b/crates/engine/src/cmd/typecmd/block_tests.rs @@ -672,6 +672,109 @@ fn point_type_with_nothing_to_fit_is_left_as_it_is() { assert!(!vectorcraft_text::layout(vectorcraft_text::FontDb::global(), &t).overflow); } +/// The distances between the baselines of `t`'s lines. +fn baseline_steps(t: &TextObject) -> Vec { + let lay = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), t); + lay.lines.windows(2).map(|w| w[1].baseline - w[0].baseline).collect() +} + +/// Block owns each character's leading (its size plus the line gap): a leading change from +/// `text.setStyle`, `text.setRangeStyle` or `type.step` on area type with Block on changes the +/// line gap by the difference from the first character's leading, in one undo step, and sticks. +#[test] +fn a_leading_change_with_block_on_moves_the_line_gap() { + let mut s = session(); + let id = area(&mut s, 300.0, 400.0, "BIG\na much longer second line\nmid one"); + s.execute("type.dynamicText", &json!({"on": true})).unwrap(); + let t = text(&s, id); + let (first, second) = (t.runs[0].style.size, size_at(&t, 4)); + let steps = baseline_steps(&t); + let n = undo_len(&s); + + // The whole object: the first character's leading becomes the leading given. + s.execute("text.setStyle", &json!({"ids": [id], "leading": first + 6.0})).unwrap(); + assert_eq!(undo_len(&s), n + 1, "one undo step"); + let t = text(&s, id); + assert!((t.area.line_gap - 6.0).abs() < 1e-9, "line gap {}", t.area.line_gap); + assert!(t.runs.iter().all(|r| r.style.leading.is_some_and(|l| (l - r.style.size - 6.0).abs() < 1e-9)), "{:?}", t.runs); + assert_block(&t); + let wider = baseline_steps(&t); + assert!(wider.iter().zip(&steps).all(|(w, s)| (w - s - 6.0).abs() < 1e-6), "every line spreads: {steps:?} -> {wider:?}"); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(text(&s, id).area.line_gap, 0.0); + + // A range: measured from the leading of its first character. + s.execute("text.setRangeStyle", &json!({"id": id, "start": 4, "end": 10, "leading": second - 3.0})).unwrap(); + let t = text(&s, id); + assert!((t.area.line_gap + 3.0).abs() < 1e-9, "line gap {}", t.area.line_gap); + assert!(baseline_steps(&t).iter().zip(&steps).all(|(w, s)| w < s), "every line tightens"); + + // Alt+Up/Down steps by the Size/Leading increment. + let inc = s.prefs.type_size_increment; + s.execute("type.step", &json!({"attribute": "leading", "by": 1, "id": id, "start": 0, "end": 3})).unwrap(); + assert!((text(&s, id).area.line_gap - (inc - 3.0)).abs() < 1e-9); + + // Auto: the first character's Auto leading, 120% of its size. + s.execute("text.setStyle", &json!({"ids": [id], "leading": "auto"})).unwrap(); + let t = text(&s, id); + assert!((t.area.line_gap - t.runs[0].style.size * 0.2).abs() < 1e-6, "line gap {}", t.area.line_gap); + + // The leading the first character already has changes nothing. + let n = undo_len(&s); + let lead = text(&s, id).runs[0].style.leading.unwrap(); + s.execute("text.setStyle", &json!({"ids": [id], "leading": lead})).unwrap(); + assert_eq!(undo_len(&s), n, "no undo step"); + + // The gap stays within its range. + s.execute("text.setStyle", &json!({"ids": [id], "leading": 5000})).unwrap(); + assert_eq!(text(&s, id).area.line_gap, 1296.0); + // From a gap that holds every leading at its least, the leading given still applies. + s.execute("text.areaOptions", &json!({"lineGap": -1296})).unwrap(); + s.execute("text.setStyle", &json!({"ids": [id], "leading": 1})).unwrap(); + let lead = text(&s, id).runs[0].style.leading.unwrap(); + assert!((lead - 1.0).abs() < 1e-6, "leading {lead}"); + s.execute("text.areaOptions", &json!({"lineGap": 0})).unwrap(); + // A size set with the leading: the gap follows the size Block gives the first character, on an + // empty line (whose size Block keeps) too. + s.execute("text.setStyle", &json!({"ids": [id], "size": 20, "leading": 50})).unwrap(); + let lead = text(&s, id).runs[0].style.leading.unwrap(); + assert!((lead - 50.0).abs() < 1e-6, "leading {lead}"); + s.execute("text.setText", &json!({"text": "\nwords"})).unwrap(); + s.execute("text.setStyle", &json!({"ids": [id], "size": 20, "leading": 30})).unwrap(); + let t = text(&s, id); + assert_eq!(size_at(&t, 0), 20.0, "the empty line keeps the size set"); + assert!((t.runs[0].style.leading.unwrap() - 30.0).abs() < 1e-6, "{:?}", t.runs[0].style); + s.execute("text.setText", &json!({"text": "BIG\na much longer second line\nmid one"})).unwrap(); + s.execute("text.areaOptions", &json!({"lineGap": 0})).unwrap(); + + // Scaled type: the leading given and the line gap are in document points. + s.execute("object.scale", &json!({"sx": 200, "sy": 200})).unwrap(); + let points = text(&s, id).style_scale().unwrap().points; + s.execute("text.setStyle", &json!({"ids": [id], "leading": 150})).unwrap(); + let t = text(&s, id); + let (size, lead) = (t.runs[0].style.size * points, t.runs[0].style.leading.unwrap() * points); + assert!((lead - 150.0).abs() < 1e-6, "leading {lead}"); + assert!((t.area.line_gap - (150.0 - size)).abs() < 1e-6, "line gap {} for size {size}", t.area.line_gap); +} + +/// Without Block (point type, and area type with Block off) a leading change sets the +/// characters' leading and leaves the line gap. +#[test] +fn a_leading_change_without_block_sets_the_leading() { + let mut s = session(); + let id = area(&mut s, 300.0, 400.0, "one\ntwo"); + s.execute("text.areaOptions", &json!({"lineGap": 5})).unwrap(); + s.execute("text.setStyle", &json!({"ids": [id], "leading": 30})).unwrap(); + let t = text(&s, id); + assert_eq!(t.area.line_gap, 5.0); + assert!(t.runs.iter().all(|r| r.style.leading == Some(30.0))); + let id = point(&mut s, "one\ntwo", json!({})); + s.execute("type.step", &json!({"attribute": "leading", "by": 1, "id": id, "start": 0, "end": 3})).unwrap(); + let t = text(&s, id); + assert_eq!(t.area.line_gap, 0.0); + assert_eq!(t.runs[0].style.leading, Some(12.0 * 1.2 + s.prefs.type_size_increment)); +} + #[test] fn long_text_fits_in_a_bounded_number_of_layouts() { let mut s = session(); @@ -698,3 +801,109 @@ fn long_text_fits_in_a_bounded_number_of_layouts() { let bound = 2 * (2 + 2 * super::block::BLOCK_PASSES as u64) + 8; assert!(used <= bound, "point type: {used} layouts"); } + +/// Area type with Block on, its lines at different sizes, and a line gap of 0. +fn block_text(s: &mut Session) -> u64 { + let id = area(s, 300.0, 400.0, "BIG\na much longer second line\nmid one"); + s.execute("type.dynamicText", &json!({"on": true})).unwrap(); + assert_eq!(text(s, id).area.line_gap, 0.0); + id +} + +/// The leading of the one-byte character at `byte` (`style_at` reads the character before a run +/// end, so it is asked for the end of the character). +fn leading_at(t: &TextObject, byte: usize) -> Option { + vectorcraft_text::edit::style_at(&t.runs, byte + 1).leading +} + +/// `text.setRangeStyle {leading}` on a range of Block text moves the line gap by the change to +/// the leading of the range's first character, and the range keeps the leading given. +#[test] +fn a_range_leading_change_with_block_on_moves_the_line_gap() { + let mut s = session(); + let id = block_text(&mut s); + let second = vectorcraft_text::edit::style_at(&text(&s, id).runs, 5).size; + s.execute("text.setRangeStyle", &json!({"id": id, "start": 4, "end": 10, "leading": second + 5.0})).unwrap(); + let t = text(&s, id); + assert!((t.area.line_gap - 5.0).abs() < 1e-9, "line gap {}", t.area.line_gap); + assert!(leading_at(&t, 4).is_some_and(|l| (l - second - 5.0).abs() < 1e-9), "{:?}", leading_at(&t, 4)); + assert!(t.runs.iter().all(|r| r.style.leading.is_some_and(|l| (l - r.style.size - 5.0).abs() < 1e-9)), "every line spreads"); + // Reset Panel's form: the leading is set and Block keeps the line gap. + s.execute("text.setRangeStyle", &json!({"id": id, "start": 4, "end": 10, "leading": "auto", "keepLineGap": true})).unwrap(); + assert!((text(&s, id).area.line_gap - 5.0).abs() < 1e-9); + s.execute("text.setStyle", &json!({"ids": [id], "leading": "auto", "keepLineGap": true})).unwrap(); + assert!((text(&s, id).area.line_gap - 5.0).abs() < 1e-9); + assert!(s.execute("text.setStyle", &json!({"ids": [id], "leading": 30, "keepLineGap": 1})).is_err(), "keepLineGap takes a bool"); +} + +/// `type.step {attribute: "leading"}` (Alt+Up/Down) on Block text moves the line gap by the step. +#[test] +fn a_leading_step_with_block_on_moves_the_line_gap() { + let mut s = session(); + let id = block_text(&mut s); + let inc = s.prefs.type_size_increment; + s.execute("type.step", &json!({"attribute": "leading", "by": -1, "id": id, "start": 0, "end": 3})).unwrap(); + let t = text(&s, id); + assert!((t.area.line_gap + inc).abs() < 1e-9, "line gap {}", t.area.line_gap); + assert!(leading_at(&t, 0).is_some_and(|l| (l - t.runs[0].style.size + inc).abs() < 1e-9)); +} + +/// A character style edited to set a leading while Block text uses it moves the line gap; a style +/// without a leading leaves the gap. +#[test] +fn a_character_style_edited_to_a_leading_with_block_on_moves_the_line_gap() { + let mut s = session(); + let id = block_text(&mut s); + s.execute("charStyle.new", &json!({"name": "Plain", "attrs": {"tracking": 0}})).unwrap(); + s.execute("charStyle.apply", &json!({"name": "Plain", "id": id})).unwrap(); + assert_eq!(text(&s, id).area.line_gap, 0.0, "no leading in the style"); + s.execute("charStyle.edit", &json!({"name": "Plain", "to": "Plain", "attrs": {"tracking": 0, "leading": 60}})).unwrap(); + let t = text(&s, id); + assert!((t.area.line_gap - (60.0 - t.runs[0].style.size)).abs() < 1e-6, "edit: line gap {}", t.area.line_gap); + assert!(leading_at(&t, 0).is_some_and(|l| (l - 60.0).abs() < 1e-6)); +} + +/// A character style that sets a leading, applied to Block text, moves the line gap. +#[test] +fn a_character_style_leading_applied_with_block_on_moves_the_line_gap() { + let mut s = session(); + let id = block_text(&mut s); + s.execute("charStyle.new", &json!({"name": "Loose", "attrs": {"leading": 50}})).unwrap(); + s.execute("charStyle.apply", &json!({"name": "Loose", "id": id})).unwrap(); + let t = text(&s, id); + assert!((t.area.line_gap - (50.0 - t.runs[0].style.size)).abs() < 1e-6, "apply: line gap {}", t.area.line_gap); + assert!(leading_at(&t, 0).is_some_and(|l| (l - 50.0).abs() < 1e-6)); + + // Clearing overrides gives the text the leading of the Normal style. + s.execute("charStyle.setAttrs", &json!({"name": "[Normal Character Style]", "attrs": {"leading": 44}})).unwrap(); + s.execute("charStyle.new", &json!({"name": "Plain", "attrs": {"tracking": 0}})).unwrap(); + s.execute("text.areaOptions", &json!({"lineGap": 0})).unwrap(); + s.execute("charStyle.apply", &json!({"name": "Plain", "id": id, "clearOverrides": true})).unwrap(); + let t = text(&s, id); + assert!(leading_at(&t, 0).is_some_and(|l| (l - 44.0).abs() < 1e-6), "clear: {:?}", leading_at(&t, 0)); +} + +/// Text Tweaker's leading ramp on Block text moves the line gap to its first character's value. +#[test] +fn a_text_tweaker_leading_with_block_on_moves_the_line_gap() { + let mut s = session(); + let id = block_text(&mut s); + s.execute("addon.type.textTweaker", &json!({"attribute": "leading", "from": 40, "to": 45, "ids": [id]})).unwrap(); + let t = text(&s, id); + assert!((t.area.line_gap - (40.0 - t.runs[0].style.size)).abs() < 1e-6, "line gap {}", t.area.line_gap); + assert!(leading_at(&t, 0).is_some_and(|l| (l - 40.0).abs() < 1e-6)); +} + +/// The Eyedropper copying a leading onto Block text moves the line gap, so the first character +/// takes the copied leading. +#[test] +fn an_eyedropper_leading_with_block_on_moves_the_line_gap() { + let mut s = session(); + let source = point(&mut s, "source", json!({})); + s.execute("text.setStyle", &json!({"ids": [source], "leading": 33})).unwrap(); + let id = block_text(&mut s); + s.execute("appearance.copyFrom", &json!({"source": source, "ids": [id]})).unwrap(); + let t = text(&s, id); + assert!(t.area.line_gap != 0.0, "the line gap moved"); + assert!(leading_at(&t, 0).is_some_and(|l| (l - 33.0).abs() < 1e-6), "{:?}", leading_at(&t, 0)); +} diff --git a/crates/engine/src/cmd/typemenu.rs b/crates/engine/src/cmd/typemenu.rs index b66a50bc19..5f61bbae81 100644 --- a/crates/engine/src/cmd/typemenu.rs +++ b/crates/engine/src/cmd/typemenu.rs @@ -84,7 +84,7 @@ pub fn specs() -> Vec { "Dynamic Text", ["Type"], None, - "{ids?|id?, on?: bool, wordGap?: % of a word space 0..1000 (100), lineGap?: pt -1296..1296 (0)} turn Dynamic Text on or off for the selected type on a path and area type, or turn it on for point type (on omitted: the opposite of the first object's setting, point type counting as off, or on when a gap is given). On type on a path, the layout scales the text by one factor (every character's size, leading and baseline shift; Type on a Path Options › Spacing stays) so that it fills the span between its start and end brackets, larger or smaller, and fits it again after every edit to the text, the path or the brackets; the first character's size moves in steps of 0.1 pt within 0.1 to 1,296 pt, and at 0.1 pt text that still runs past the end bracket overflows. The stored sizes keep their proportions. On area type it is Block: each line as typed (each paragraph, and each forced line break in one; lines are not broken again) is set to the frame's width, less the inset, the gutters and the paragraph's indents, by changing its font size only: its first character's size, in steps of 0.1 pt within 0.1 to 1,296 pt, the line's other characters keeping their proportions to it, with baseline shifts following. Every character's leading is its size plus lineGap, and the layout sets every paragraph with wordGap as its Desired word spacing, its Minimum or Maximum moving out to wordGap when wordGap lies outside it (the paragraphs keep their own Justification… values, which apply again when Block is off; the gaps are area type's, and are kept while Block is off; a gap with no area type in the selection, and no point type it turns into area type, is an error). The sizes are written into the characters and fitted again after every edit to the text or the frame, in the same undo step; at a size limit a line can be narrower than the frame or wrap. An empty line keeps its size. Block replaces Auto Size and Shrink Text to Fit (Area Type Options › Block is the same setting). Off, the text keeps the sizes it was drawn at. Turning it on turns point type into area type with Block on, with the default Area Type Options but the gaps (options kept from an earlier frame do not carry over): the frame is as wide (along the lines) as the widest line as typed with its paragraph's indents, so that line keeps its size and sits where it was (by its own alignment), the other lines are set to that width (when negative indents take more than that line's width, the frame is as wide as the line, and Block makes it larger), and the frame then grows in depth (down, or to the left for vertical type) to hold every fitted line, around any Text Wrap objects above it; the gaps apply to it as to area type. Point type with no line to fit (empty, or only spaces and breaks) is left as it is, and so is point type when it is turned off; a selection holding type in a thread is refused (threading type turns Dynamic Text off, keeping its drawn sizes). When nothing changes, no undo step is recorded → {on, ids, fitScale (the first object's factor; 1 when off and for area type), wordGap?, lineGap? (the first area type's; left out without area type)}", + "{ids?|id?, on?: bool, wordGap?: % of a word space 0..1000 (100), lineGap?: pt -1296..1296 (0)} turn Dynamic Text on or off for the selected type on a path and area type, or turn it on for point type (on omitted: the opposite of the first object's setting, point type counting as off, or on when a gap is given). On type on a path, the layout scales the text by one factor (every character's size, leading and baseline shift; Type on a Path Options › Spacing stays) so that it fills the span between its start and end brackets, larger or smaller, and fits it again after every edit to the text, the path or the brackets; the first character's size moves in steps of 0.1 pt within 0.1 to 1,296 pt, and at 0.1 pt text that still runs past the end bracket overflows. The stored sizes keep their proportions. On area type it is Block: each line as typed (each paragraph, and each forced line break in one; lines are not broken again) is set to the frame's width, less the inset, the gutters and the paragraph's indents, by changing its font size only: its first character's size, in steps of 0.1 pt within 0.1 to 1,296 pt, the line's other characters keeping their proportions to it, with baseline shifts following. Every character's leading is its size plus lineGap (a leading change on the text, from text.setStyle, text.setRangeStyle, type.step, a character style, the Eyedropper or Text Tweaker, sets lineGap to the new leading less the size of the first character changed), and the layout sets every paragraph with wordGap as its Desired word spacing, its Minimum or Maximum moving out to wordGap when wordGap lies outside it (the paragraphs keep their own Justification… values, which apply again when Block is off; the gaps are area type's, and are kept while Block is off; a gap with no area type in the selection, and no point type it turns into area type, is an error). The sizes are written into the characters and fitted again after every edit to the text or the frame, in the same undo step; at a size limit a line can be narrower than the frame or wrap. An empty line keeps its size. Block replaces Auto Size and Shrink Text to Fit (Area Type Options › Block is the same setting). Off, the text keeps the sizes it was drawn at. Turning it on turns point type into area type with Block on, with the default Area Type Options but the gaps (options kept from an earlier frame do not carry over): the frame is as wide (along the lines) as the widest line as typed with its paragraph's indents, so that line keeps its size and sits where it was (by its own alignment), the other lines are set to that width (when negative indents take more than that line's width, the frame is as wide as the line, and Block makes it larger), and the frame then grows in depth (down, or to the left for vertical type) to hold every fitted line, around any Text Wrap objects above it; the gaps apply to it as to area type. Point type with no line to fit (empty, or only spaces and breaks) is left as it is, and so is point type when it is turned off; a selection holding type in a thread is refused (threading type turns Dynamic Text off, keeping its drawn sizes). When nothing changes, no undo step is recorded → {on, ids, fitScale (the first object's factor; 1 when off and for area type), wordGap?, lineGap? (the first area type's; left out without area type)}", has_dynamic_type, dynamic_text ), diff --git a/crates/ui-egui/src/panels/character.rs b/crates/ui-egui/src/panels/character.rs index 1cb759fa69..f8b6b283e4 100644 --- a/crates/ui-egui/src/panels/character.rs +++ b/crates/ui-egui/src/panels/character.rs @@ -1871,8 +1871,9 @@ fn fractional_widths_on(app: &VectorcraftApp) -> bool { /// line gap, 50%, Auto alignment), Insert Aki Left and Right 0, Tsume 0, the Default character direction, /// Kashidas on, the Default digits, Adjust Horizontal and Vertical Diacritic Position 0 and the Em Box /// font height reference, whether or not Show East Asian -/// Options, Show Indic Options and Show Font Height Options are on. Inside an undo group that is -/// already open, the reset is part of that group's step. +/// Options, Show Indic Options and Show Font Height Options are on. Area type with Dynamic Text +/// (Block) on keeps its frame's Line Gap. Inside an undo group that is already open, the reset is +/// part of that group's step. fn reset_panel(app: &mut VectorcraftApp) { // Typing in progress stays an undo step of its own. end_typing(app); @@ -1881,7 +1882,8 @@ fn reset_panel(app: &mut VectorcraftApp) { app.session.begin_named_undo_group(Some("Reset Panel".into())); } let d = CharStyle::default(); - style(app, json!({"tracking": 0, "leading": "auto"})); + // Dynamic Text's Line Gap is the frame's, so the reset leaves it as it is. + style(app, json!({"tracking": 0, "leading": "auto", "keepLineGap": true})); format( app, json!({ diff --git a/crates/ui-egui/src/panels/character/tests.rs b/crates/ui-egui/src/panels/character/tests.rs index c6e43871ad..0434c9c89a 100644 --- a/crates/ui-egui/src/panels/character/tests.rs +++ b/crates/ui-egui/src/panels/character/tests.rs @@ -185,6 +185,118 @@ fn leading_follows_the_paragraphs_the_type_tool_selection_covers() { } } +/// Selected area type of two equal lines with Dynamic Text (Block) on and a Line Gap of 7 pt. +fn block_app() -> (VectorcraftApp, NodeId) { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 600, "height": 400})).unwrap(); + let id = + app.run("text.create", json!({"x": 20, "y": 20, "size": 12, "area": {"width": 300, "height": 2000}, "text": "Hello\nHello"})).unwrap()["id"] + .as_u64() + .unwrap(); + app.run("select.set", json!({"ids": [id]})).unwrap(); + app.run("type.dynamicText", json!({"on": true, "lineGap": 7})).unwrap(); + let leading = shared_leading(&app).expect("both lines share a leading"); + assert!((leading - block_text(&app, NodeId(id)).runs[0].style.size - 7.0).abs() < 1e-9); + (app, NodeId(id)) +} + +fn block_text(app: &VectorcraftApp, id: NodeId) -> vectorcraft_doc::TextObject { + match &app.session.active().unwrap().doc.node(id).unwrap().kind { + NodeKind::Text(t) => (**t).clone(), + _ => panic!("text"), + } +} + +/// Focuses the field of `panel` that shows the leading (the Font Size field reads 7 pt less). +fn focus_leading_field(ctx: &egui::Context, app: &mut VectorcraftApp, panel: fn(&mut VectorcraftApp, &mut egui::Ui)) { + use super::super::tests_appearance::{click, frame_events, text_rect}; + let leading = shared_leading(app).expect("a shared leading"); + let texts = frame_events(ctx, app, vec![], panel); + let field = texts + .iter() + .find(|(s, _)| s.trim_end_matches(" pt").trim().parse::().is_ok_and(|v| (v - leading).abs() < 0.05)) + .map(|(s, _)| s.clone()) + .expect("the Leading field shows the leading"); + click(ctx, app, text_rect(&texts, &field).center(), panel); +} + +fn key_event(key: egui::Key, modifiers: egui::Modifiers) -> egui::Event { + egui::Event::Key { key, physical_key: None, pressed: true, repeat: false, modifiers } +} + +/// Types `value` into the Leading field of `panel` and presses Enter. +fn type_leading(app: &mut VectorcraftApp, panel: fn(&mut VectorcraftApp, &mut egui::Ui), value: &str) { + use super::super::tests_appearance::frame_events; + let ctx = egui::Context::default(); + focus_leading_field(&ctx, app, panel); + frame_events(&ctx, app, vec![key_event(egui::Key::A, egui::Modifiers::COMMAND)], panel); + frame_events(&ctx, app, vec![egui::Event::Text(value.into())], panel); + frame_events(&ctx, app, vec![key_event(egui::Key::Enter, egui::Modifiers::NONE)], panel); + frame_events(&ctx, app, vec![], panel); +} + +/// Picks `entry` from the Leading field's list (opened with Alt+↓) in the Character panel. +fn pick_leading(app: &mut VectorcraftApp, entry: &str) { + use super::super::tests_appearance::{click, frame_events, text_rect}; + let ctx = egui::Context::default(); + focus_leading_field(&ctx, app, show); + frame_events(&ctx, app, vec![key_event(egui::Key::ArrowDown, egui::Modifiers::ALT)], show); + let texts = frame_events(&ctx, app, vec![], show); + // The list is drawn last, above the panel. + let rect = texts.iter().rev().find(|(s, _)| s == entry).map(|(_, r)| *r).unwrap_or_else(|| text_rect(&texts, entry)); + click(&ctx, app, rect.center(), show); + frame_events(&ctx, app, vec![], show); +} + +/// Area type with Dynamic Text (Block) on: a leading typed into the Leading field moves the +/// frame's Line Gap, so the field then shows the leading typed and the lines are spaced by it. +#[test] +fn leading_typed_with_block_on_moves_the_line_gap() { + let (mut app, id) = block_app(); + let size = block_text(&app, id).runs[0].style.size; + type_leading(&mut app, show, "200"); + let t = block_text(&app, id); + assert!((t.area.line_gap - (200.0 - size)).abs() < 1e-6, "line gap {} for size {size}", t.area.line_gap); + assert!(shared_leading(&app).is_some_and(|l| (l - 200.0).abs() < 1e-6), "the field shows {:?}", shared_leading(&app)); + let lay = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), &t); + assert!((lay.lines[1].baseline - lay.lines[0].baseline - 200.0).abs() < 1e-6, "the lines are 200 pt apart"); +} + +/// The Properties panel's Leading field does the same on Block text. +#[test] +fn leading_typed_in_properties_with_block_on_moves_the_line_gap() { + let (mut app, id) = block_app(); + let size = block_text(&app, id).runs[0].style.size; + type_leading(&mut app, super::super::properties::show, "150"); + let t = block_text(&app, id); + assert!((t.area.line_gap - (150.0 - size)).abs() < 1e-6, "line gap {} for size {size}", t.area.line_gap); +} + +/// A pick from the Leading field's list on Block text: a preset, then Auto, each moves the Line Gap. +#[test] +fn leading_picked_from_the_list_with_block_on_moves_the_line_gap() { + let (mut app, id) = block_app(); + let size = block_text(&app, id).runs[0].style.size; + let preset = vectorcraft_doc::Unit::Points.format(72.0); + pick_leading(&mut app, &preset); + let gap = block_text(&app, id).area.line_gap; + assert!((gap - (72.0 - size)).abs() < 1e-6, "{preset}: line gap {gap} for size {size}"); + pick_leading(&mut app, tl!("Auto")); + let gap = block_text(&app, id).area.line_gap; + assert!(gap > 0.0 && gap < size * 0.5, "Auto: line gap {gap} for size {size}"); +} + +/// Reset Panel resets the leading to Auto and leaves Block's Line Gap, which belongs to the frame. +#[test] +fn reset_panel_with_block_on_keeps_the_line_gap() { + let (mut app, id) = block_app(); + app.run("text.setFormat", json!({"baselineShift": 3})).unwrap(); + reset_panel(&mut app); + let t = block_text(&app, id); + assert_eq!(t.area.line_gap, 7.0); + assert_eq!(t.runs[0].style.baseline_shift, 0.0, "the reset ran"); +} + #[test] fn scaled_range_fields_follow_the_type_tool_selection() { let mut app = VectorcraftApp::new(Session::new(), Default::default()); diff --git a/docs/mcp.md b/docs/mcp.md index fe69653330..7a1373b938 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -11324,6 +11324,22 @@ lines. The rest are VectorCraft's own rules: Maximum word spacing moves out to `wordGap` when `wordGap` lies outside it. The paragraphs keep their own Justification… values, which apply again when Block is off. Each character's leading is its size plus `lineGap`. A gap given with no area type in the selection, and no point type that it turns into area type, is an error. +- A leading change on the frame's text sets `lineGap` to the new leading less the size of the first character changed, + within -1,296 to 1,296 pt, in the change's own undo step. That covers `text.setStyle {leading}` and + `text.setRangeStyle {leading}` (the Character panel's and the Properties panel's Leading field and its list), + `type.step {attribute: "leading"}` (the Type tool's Alt+arrow leading steps), `charStyle.apply` with a style that sets + a leading (or with `clearOverrides` when the Normal style sets one), `charStyle.edit` and `charStyle.setAttrs` when + the new definition gives its users another leading, `appearance.copyFrom` copying character attributes (the + Eyedropper) and `addon.type.textTweaker {attribute: "leading"}` (from its first changed character). `"auto"` takes + the first character's Auto leading. Every line then spreads or tightens by the change to that character's leading. + In a shaped frame where the moved lines take another size, the gap is worked out again from the new size, up to four + times, and the leading set can then differ by the last change in that size. Area Type Options and the Properties + panel show the new Line Gap. When the changed characters share one size and the gap is within its range, the Leading + field shows the leading set. Otherwise each character takes its own size plus the gap, and the field is blank where + those differ. + `keepLineGap: true` on `text.setStyle` and `text.setRangeStyle` leaves `lineGap` as it is, and the Character panel's + Reset Panel sends it, so a reset to Auto leading keeps the frame's Line Gap. Point type, type on a path and area type + with Block off keep their own leading. - The sizes are written into the characters, so every export and the Character panel see them. After every edit to the text or the frame (typing, `text.editRange`, character and paragraph changes, `text.areaOptions {width}`, a frame resize) the lines are fitted again, in the edit's own undo step. The lines are then measured again, in at diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index eeb3a0c818..19083cb60f 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1795,7 +1795,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur Type › Type on a Path › Center on Top and Center on Bottom (`type.pathCenter.top`, `type.pathCenter.bottom`, also on the Contextual Task Bar for type on a closed path) slide type on a closed path so the middle of its span lands on the path's topmost or bottommost point as drawn, keep the span's length, and set the first paragraph to Center unless it is Center or Justify Center. This is VectorCraft's own behavior (`crates/geom/src/arc.rs`, `crates/engine/src/tests/pathtype.rs`). Type on a Path Options › Align to Path (option names as in [Create type on a path](https://helpx.adobe.com/illustrator/desktop/design-with-text/edit-format-text/create-type-on-a-path.html)) moves each character by its own font, size and vertical scale: Ascender runs the top of the font's em box along the path (the ideographic em box that its `BASE` table, its typographic or `hhea` box or its ideographs give, else an em box centered on the cap height), Descender runs the bottom of the font's bounding box along it, and Center runs a line at half the height of the top of the font's H above the baseline along it. In vertical type, Ascender and Descender move the characters half an em, and Center leaves them on the path. These distances are VectorCraft's own values (`tests::on_path_align_runs_each_glyph_by_its_own_metrics`, `tests::on_path_align_finds_the_em_box_of_each_kind_of_face`, `tests::on_path_align_in_vertical_type_moves_half_an_em`). Type › Dynamic Text (`type.dynamicText`, also on the Contextual Task Bar for type on a path) sizes type on a path to fill the span between its start and end brackets and fits it again after each edit to the text or a bracket ([Dynamic Text overview](https://helpx.adobe.com/photoshop/desktop/text-typography/work-with-dynamic-text/dynamic-text-overview.html), [start and end points](https://helpx.adobe.com/photoshop/desktop/text-typography/work-with-dynamic-text/reposition-start-and-end-points.html)). VectorCraft's own rules: reshaping or scaling the path fits the text again; one factor scales every size, leading and baseline shift; the first character's size moves in 0.1 pt steps within 0.1 to 1,296 pt; turning it off, threading the type or Release Type on a Path keeps the drawn sizes; SVG, EPS, legacy `.ai` and the editing data write the drawn sizes (`crates/text/src/tests/fit.rs`, `crates/engine/src/tests/dynamic_text.rs`). - Dynamic Text on area type is Block (Type › Dynamic Text, the Contextual Task Bar, Area Type Options › Block, the Properties panel's Dynamic Text checkbox with Word Gap and Line Gap; [Dynamic Text overview](https://helpx.adobe.com/photoshop/desktop/text-typography/work-with-dynamic-text/dynamic-text-overview.html)): each line as typed is set to the frame's width by its font size, again after every edit to the text or the frame. VectorCraft's own rules: lines are not broken again, the first character's size moves in 0.1 pt steps within 0.1 to 1,296 pt, Word Gap (0 to 1,000 %, default 100) is the Desired word spacing and Line Gap (-1,296 to 1,296 pt, default 0) is added to each size for the leading, the sizes are written into the characters, threaded frames cannot use it, and Convert To Point Type turns it off, keeping the sizes (`crates/engine/src/cmd/typecmd/block_tests.rs`). + Dynamic Text on area type is Block (Type › Dynamic Text, the Contextual Task Bar, Area Type Options › Block, the Properties panel's Dynamic Text checkbox with Word Gap and Line Gap; [Dynamic Text overview](https://helpx.adobe.com/photoshop/desktop/text-typography/work-with-dynamic-text/dynamic-text-overview.html)): each line as typed is set to the frame's width by its font size, again after every edit to the text or the frame. VectorCraft's own rules: lines are not broken again, the first character's size moves in 0.1 pt steps within 0.1 to 1,296 pt, Word Gap (0 to 1,000 %, default 100) is the Desired word spacing and Line Gap (-1,296 to 1,296 pt, default 0) is added to each size for the leading, a leading change (the Character and Properties panels, the Type tool's Alt+arrow leading steps, a character style, the Eyedropper, Text Tweaker) sets Line Gap to the new leading less the size of the first character changed, Reset Panel keeps Line Gap, the sizes are written into the characters, threaded frames cannot use it, and Convert To Point Type turns it off, keeping the sizes (`crates/engine/src/cmd/typecmd/block_tests.rs`). Dynamic Text on point type (Type › Dynamic Text, the Contextual Task Bar; [Adjust formatting and resize text](https://helpx.adobe.com/photoshop/desktop/text-typography/work-with-dynamic-text/adjust-formatting-and-resize-text-with-dynamic-text.html) applies it to existing text) turns it into area type with Block on. VectorCraft's own rules: the frame is as wide as the widest line with its indents, so that line keeps its size and place across the page, and it grows in depth to hold every fitted line (`crates/engine/src/cmd/typecmd/block_tests.rs`). Type › Dynamic Text Presets › Circle, Arch and Bow (`type.dynamicTextPreset`) put point type or type on a path on a circular, upward-curving or downward-curving path with Dynamic Text on, with the text's position against the path (above, center, below) and its direction ([Dynamic Text overview](https://helpx.adobe.com/photoshop/desktop/text-typography/work-with-dynamic-text/dynamic-text-overview.html)). VectorCraft's own rules: the circle is as wide as the text and the text starts at its bottom; Arch and Bow are a 120° arc whose chord is as wide as the text; above, center and below are Align to Path's Descender, Center and Ascender (`crates/engine/src/tests/dynamic_text.rs`). The frames of threaded text share one Optical Margin Alignment setting: turning it on or off in one frame sets it in every frame, threading frames gives the thread its first frame's setting, and frames taken out of a thread keep it. From ba69dd9feb6e0f004568a1d71c999e65b3648007 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 01:57:03 -0800 Subject: [PATCH 030/151] Color Effects: the Adjustment menu names each effect as History does The panel's Adjustment menu showed each adjustment by the plain row of its English label, while Apply as Filter records a step that History and Edit > Undo name from the effect's Effect menu row. In German the menu said "Stufen" and the step "Tonwertkorrektur". The menu now takes its names from i18n::effect_name. --- crates/ui-egui/src/addons/color.rs | 14 +++++++++--- crates/ui-egui/src/addons/color/tests.rs | 27 ++++++++++++++++++++++++ 2 files changed, 38 insertions(+), 3 deletions(-) diff --git a/crates/ui-egui/src/addons/color.rs b/crates/ui-egui/src/addons/color.rs index 39c73e8c64..d3358dbbf3 100644 --- a/crates/ui-egui/src/addons/color.rs +++ b/crates/ui-egui/src/addons/color.rs @@ -88,6 +88,12 @@ fn adjustment(i: usize) -> (&'static str, &'static str, &'static [Field]) { ADJUSTMENTS.get(i).copied().unwrap_or(ADJUSTMENTS[0]) } +/// The adjustments' names in `lang`, in [`ADJUSTMENTS`] order: each effect's name as the Effect +/// menu, History and Edit › Undo show it ([`crate::i18n::effect_name`]). +fn adjustment_names(lang: crate::i18n::Lang) -> Vec { + ADJUSTMENTS.iter().map(|a| crate::i18n::effect_name(lang, a.0).unwrap_or_else(|| crate::i18n::tr(lang, a.1).to_string())).collect() +} + /// Object › Plug-ins › Color Effects. pub fn menu() -> Vec { let cmd = |(label, id, p): (&'static str, &'static str, Value)| Item::Cmd(label, id, p); @@ -150,11 +156,13 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { return; } let mut st: Picked = pstate(ui.ctx(), STATE); - let labels: Vec<&str> = ADJUSTMENTS.iter().map(|a| a.1).collect(); - let (id, label, fields) = adjustment(st.index); + let names = adjustment_names(crate::i18n::current()); + let labels: Vec<&str> = names.iter().map(String::as_str).collect(); + let (id, _, fields) = adjustment(st.index); + let current = ADJUSTMENTS.iter().position(|a| a.0 == id).and_then(|i| labels.get(i)).copied().unwrap_or_default(); const LABEL_W: f32 = 84.0; widgets::label_row(ui, tl!("Adjustment"), LABEL_W, |ui| { - if let Some(i) = widgets::dropdown(ui, "color-effects-pick", label, &labels, 150.0) { + if let Some(i) = widgets::dropdown_names(ui, "color-effects-pick", current, &labels, 150.0) { st.index = i; } }); diff --git a/crates/ui-egui/src/addons/color/tests.rs b/crates/ui-egui/src/addons/color/tests.rs index 7ba046c72e..e787a85e93 100644 --- a/crates/ui-egui/src/addons/color/tests.rs +++ b/crates/ui-egui/src/addons/color/tests.rs @@ -46,6 +46,33 @@ fn every_adjustment_offered_is_a_colour_adjustment_with_its_defaults() { } } +/// Apply as Filter records a step that History and Edit › Undo name as the panel names the +/// adjustment, in every language (German's plain `Levels` row and its Effect menu row differ). +#[test] +fn history_names_a_filter_step_as_the_panel_names_its_adjustment() { + for (i, (id, _, fields)) in ADJUSTMENTS.iter().enumerate() { + let mut app = app(); + app.run("paint.setFill", json!({"color": "#806040"})).unwrap(); + let (_, mut params) = Picked { index: i, ..Picked::default() }.params(); + if let Some((key, _, (_, max), ..)) = fields.first() { + params[*key] = json!(max); + } + app.run("addon.color.filter", json!({ "effect": id, "params": params })).unwrap(); + let h = app.session.active().unwrap().history.undo.last().cloned().unwrap(); + assert_eq!(h.effect(), Some(*id), "the step Apply as Filter records for {params}"); + for lang in crate::i18n::Lang::all() { + crate::i18n::set_current(lang); + let step = crate::panels::history::shown(&h); + let text = painted_text(&mut app, |app, ui| { + set_pstate(ui.ctx(), STATE, Picked { index: i, ..Picked::default() }); + show(app, ui); + }); + crate::i18n::set_current(crate::i18n::Lang::EN); + assert!(text.lines().any(|line| line == step), "{} {id}: {step:?} in {text}", lang.code()); + } + } +} + #[test] fn the_panel_shows_the_values_and_its_buttons() { let mut app = app(); From e836d1e32ce89c0b45c1b1dbdfd9508a76d90891 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 02:09:25 -0800 Subject: [PATCH 031/151] Tests: History names a plain step from the menu item's row A step that applies no effect, such as Object > Path > Clean Up, takes its plain row in each language, else the menu item's row without the ellipsis. The test checks that fallback in every catalog again. --- crates/ui-egui/src/panels/history.rs | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/crates/ui-egui/src/panels/history.rs b/crates/ui-egui/src/panels/history.rs index b75b831d1c..619bd889f5 100644 --- a/crates/ui-egui/src/panels/history.rs +++ b/crates/ui-egui/src/panels/history.rs @@ -188,9 +188,15 @@ mod tests { assert_eq!(listed(&mut app)[rows.len() - 6..rows.len() - 4], ["Apply Body", "Apply {name}"]); } - /// A step name with no catalog row has no translation. + /// A step that applies no effect, named like a menu item (Object › Path › Clean Up…), takes its + /// plain row, else the menu item's row without the ellipsis; a name with no row has none. #[test] - fn unknown_steps_have_no_name() { + fn plain_steps_read_the_menu_row_and_unknown_steps_have_no_name() { + for lang in crate::i18n::Lang::all() { + let menu_row = crate::i18n::has(lang, "Clean Up…").then(|| crate::i18n::tr(lang, "Clean Up…").trim_end_matches('…').to_string()); + let plain_row = crate::i18n::has(lang, "Clean Up").then(|| crate::i18n::tr(lang, "Clean Up").to_string()); + assert_eq!(step_name(lang, "Clean Up"), plain_row.or(menu_row), "{}", lang.code()); + } let ja = crate::i18n::Lang::from_code("ja").expect("ja registered"); assert_eq!(step_name(ja, "No Such Step"), None); } From c3905aee4f76baa94dc9d0b463437e5380eab9dc Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 02:50:05 -0800 Subject: [PATCH 032/151] Dynamic Text: a style's new leading applies to Block text, the Eyedropper keeps Line Gap Block gives every character its size plus the frame's Line Gap, so on Block text a character's leading is never an override. A character style edited to a new leading now applies it there even when Block has given its users other leadings than the old definition's, for example after a Line Gap change or a refit, and the Line Gap moves. The Eyedropper copies a whole character style, so the leading it copies is no longer treated as a leading change: Line Gap stays, and Block gives the characters their size plus the gap, as before this branch. The tests now check that every character's leading is its size plus the new gap for each path, and the docs say that Text Tweaker's ramp sets the gap from its first character and does not vary the leading. --- crates/engine/src/cmd/appearance.rs | 14 +------ crates/engine/src/cmd/textstyles.rs | 10 +++++ crates/engine/src/cmd/typecmd.rs | 2 +- crates/engine/src/cmd/typecmd/block.rs | 4 +- crates/engine/src/cmd/typecmd/block_tests.rs | 39 ++++++++++++++++---- crates/engine/src/cmd/typemenu.rs | 2 +- docs/mcp.md | 16 ++++---- docs/target-app-parity.md | 2 +- 8 files changed, 57 insertions(+), 32 deletions(-) diff --git a/crates/engine/src/cmd/appearance.rs b/crates/engine/src/cmd/appearance.rs index d1d6194639..3b23d62634 100644 --- a/crates/engine/src/cmd/appearance.rs +++ b/crates/engine/src/cmd/appearance.rs @@ -2003,12 +2003,7 @@ fn copy_from(s: &mut Session, p: &Value) -> Result { if let Some((_, para)) = picked.text.as_ref().filter(|_| attrs.paragraph) { t.edit_paras(Some(t.paragraphs_in(start, end)), |p| *p = para.clone()); } - // With Block on, the copied leading goes to the frame's line gap. - if characters.contains_key(&id) && start < end { - super::typecmd::refresh_with_given_leading(t, start); - } else { - super::typecmd::refresh_bounds(t); - } + super::typecmd::refresh_bounds(t); } check_text_bounds(d)?; let labels = super::graph::capture_label_text(d, &whole, kept_text, kept_para)?; @@ -2270,12 +2265,7 @@ impl Picked { t.set_all_paras(para.clone()); } if text.is_some() && (a.character || a.paragraph) { - // With Block on, the copied leading goes to the frame's line gap. - if character.is_some() { - super::typecmd::refresh_with_given_leading(t, 0); - } else { - super::typecmd::refresh_bounds(t); - } + super::typecmd::refresh_bounds(t); } return; } diff --git a/crates/engine/src/cmd/textstyles.rs b/crates/engine/src/cmd/textstyles.rs index a804984ff6..426410b661 100644 --- a/crates/engine/src/cmd/textstyles.rs +++ b/crates/engine/src/cmd/textstyles.rs @@ -502,11 +502,21 @@ fn update_users(d: &mut Document, kind: Kind, name: &str, old: &Map>(v.clone()).ok()); match kind { Kind::Char => { let mut off = 0; for r in &mut t.runs { if r.style.style_name == target { + if let Some(l) = old_leading { + r.style.leading = l; + } let was = r.style.leading; r.style = font_change(&r.style, restyle(&r.style, char_attrs, old, new, &base), new); changed = true; diff --git a/crates/engine/src/cmd/typecmd.rs b/crates/engine/src/cmd/typecmd.rs index ea5a416165..240fb37c1f 100644 --- a/crates/engine/src/cmd/typecmd.rs +++ b/crates/engine/src/cmd/typecmd.rs @@ -359,7 +359,7 @@ pub(crate) fn refresh_with_leading(t: &mut TextObject, at: usize, leading: Optio } /// [`refresh_with_leading`] with the leading the character at `at` was just given (a character -/// style, the Eyedropper, Text Tweaker). +/// style, Text Tweaker). pub(crate) fn refresh_with_given_leading(t: &mut TextObject, at: usize) { if block::given_leading_to_line_gap(t, at) { refresh_fitted(t); diff --git a/crates/engine/src/cmd/typecmd/block.rs b/crates/engine/src/cmd/typecmd/block.rs index 8a567f127c..c3a54ca84f 100644 --- a/crates/engine/src/cmd/typecmd/block.rs +++ b/crates/engine/src/cmd/typecmd/block.rs @@ -6,7 +6,7 @@ use vectorcraft_doc::{CharStyle, TextKind, TextObject, TextRun}; /// The font size range a line's first character is fitted within, in document points (the /// Character panel's). -const SIZES: (f64, f64) = (0.1, 1296.0); +pub(crate) const SIZES: (f64, f64) = (0.1, 1296.0); /// Most passes a refit runs to correct lines that still wrap after the first fit; each pass measures /// the lines and runs at most one more area layout. @@ -194,7 +194,7 @@ pub(crate) fn leading_to_line_gap(t: &mut TextObject, at: usize, leading: Option } /// [`leading_to_line_gap`] with the leading the character at `at` was just given (a character -/// style, the Eyedropper, Text Tweaker), read before Block sets it again. +/// style, Text Tweaker), read before Block sets it again. pub(crate) fn given_leading_to_line_gap(t: &mut TextObject, at: usize) -> bool { let Some(leading) = run_at(&t.runs, at).map(|r| r.style.leading) else { return false }; leading_to_line_gap(t, at, leading) diff --git a/crates/engine/src/cmd/typecmd/block_tests.rs b/crates/engine/src/cmd/typecmd/block_tests.rs index 911f5abfd1..84d52e2cb1 100644 --- a/crates/engine/src/cmd/typecmd/block_tests.rs +++ b/crates/engine/src/cmd/typecmd/block_tests.rs @@ -727,7 +727,7 @@ fn a_leading_change_with_block_on_moves_the_line_gap() { // The gap stays within its range. s.execute("text.setStyle", &json!({"ids": [id], "leading": 5000})).unwrap(); - assert_eq!(text(&s, id).area.line_gap, 1296.0); + assert_eq!(text(&s, id).area.line_gap, vectorcraft_doc::AreaOptions::LINE_GAP.1); // From a gap that holds every leading at its least, the leading given still applies. s.execute("text.areaOptions", &json!({"lineGap": -1296})).unwrap(); s.execute("text.setStyle", &json!({"ids": [id], "leading": 1})).unwrap(); @@ -861,6 +861,25 @@ fn a_character_style_edited_to_a_leading_with_block_on_moves_the_line_gap() { let t = text(&s, id); assert!((t.area.line_gap - (60.0 - t.runs[0].style.size)).abs() < 1e-6, "edit: line gap {}", t.area.line_gap); assert!(leading_at(&t, 0).is_some_and(|l| (l - 60.0).abs() < 1e-6)); + assert_spread(&t); + + // Once Block has given the characters other leadings than the style's (a new line gap here), a + // new leading in the style still applies: Block's leadings are not overrides. + s.execute("text.areaOptions", &json!({"lineGap": 0})).unwrap(); + let gap = text(&s, id).area.line_gap; + s.execute("charStyle.edit", &json!({"name": "Plain", "to": "Plain", "attrs": {"tracking": 0, "leading": 70}})).unwrap(); + let t = text(&s, id); + assert!(t.area.line_gap != gap, "the line gap moved"); + assert!(leading_at(&t, 0).is_some_and(|l| (l - 70.0).abs() < 1e-6), "{:?}", leading_at(&t, 0)); + assert_spread(&t); +} + +/// Every character's leading is its size plus the frame's line gap (at least the least size), so +/// every line spread or tightened by the same amount. +fn assert_spread(t: &TextObject) { + let gap = t.area.line_gap; + let least = super::block::SIZES.0; + assert!(t.runs.iter().all(|r| r.style.leading.is_some_and(|l| (l - (r.style.size + gap).max(least)).abs() < 1e-6)), "{:?}", t.runs); } /// A character style that sets a leading, applied to Block text, moves the line gap. @@ -873,6 +892,7 @@ fn a_character_style_leading_applied_with_block_on_moves_the_line_gap() { let t = text(&s, id); assert!((t.area.line_gap - (50.0 - t.runs[0].style.size)).abs() < 1e-6, "apply: line gap {}", t.area.line_gap); assert!(leading_at(&t, 0).is_some_and(|l| (l - 50.0).abs() < 1e-6)); + assert_spread(&t); // Clearing overrides gives the text the leading of the Normal style. s.execute("charStyle.setAttrs", &json!({"name": "[Normal Character Style]", "attrs": {"leading": 44}})).unwrap(); @@ -881,9 +901,12 @@ fn a_character_style_leading_applied_with_block_on_moves_the_line_gap() { s.execute("charStyle.apply", &json!({"name": "Plain", "id": id, "clearOverrides": true})).unwrap(); let t = text(&s, id); assert!(leading_at(&t, 0).is_some_and(|l| (l - 44.0).abs() < 1e-6), "clear: {:?}", leading_at(&t, 0)); + assert!((t.area.line_gap - (44.0 - t.runs[0].style.size)).abs() < 1e-6, "clear: line gap {}", t.area.line_gap); + assert_spread(&t); } -/// Text Tweaker's leading ramp on Block text moves the line gap to its first character's value. +/// Text Tweaker's leading ramp on Block text moves the line gap to its first character's value; +/// Block then gives every other character its size plus that gap. #[test] fn a_text_tweaker_leading_with_block_on_moves_the_line_gap() { let mut s = session(); @@ -892,18 +915,20 @@ fn a_text_tweaker_leading_with_block_on_moves_the_line_gap() { let t = text(&s, id); assert!((t.area.line_gap - (40.0 - t.runs[0].style.size)).abs() < 1e-6, "line gap {}", t.area.line_gap); assert!(leading_at(&t, 0).is_some_and(|l| (l - 40.0).abs() < 1e-6)); + assert_spread(&t); } -/// The Eyedropper copying a leading onto Block text moves the line gap, so the first character -/// takes the copied leading. +/// The Eyedropper copies a whole character style, so the leading it copies onto Block text is not +/// a leading change: the line gap stays, and Block gives every character its size plus the gap. #[test] -fn an_eyedropper_leading_with_block_on_moves_the_line_gap() { +fn an_eyedropper_copy_onto_block_text_keeps_the_line_gap() { let mut s = session(); let source = point(&mut s, "source", json!({})); s.execute("text.setStyle", &json!({"ids": [source], "leading": 33})).unwrap(); let id = block_text(&mut s); + let gap = text(&s, id).area.line_gap; s.execute("appearance.copyFrom", &json!({"source": source, "ids": [id]})).unwrap(); let t = text(&s, id); - assert!(t.area.line_gap != 0.0, "the line gap moved"); - assert!(leading_at(&t, 0).is_some_and(|l| (l - 33.0).abs() < 1e-6), "{:?}", leading_at(&t, 0)); + assert_eq!(t.area.line_gap, gap); + assert_spread(&t); } diff --git a/crates/engine/src/cmd/typemenu.rs b/crates/engine/src/cmd/typemenu.rs index 5f61bbae81..70aa0ee07c 100644 --- a/crates/engine/src/cmd/typemenu.rs +++ b/crates/engine/src/cmd/typemenu.rs @@ -84,7 +84,7 @@ pub fn specs() -> Vec { "Dynamic Text", ["Type"], None, - "{ids?|id?, on?: bool, wordGap?: % of a word space 0..1000 (100), lineGap?: pt -1296..1296 (0)} turn Dynamic Text on or off for the selected type on a path and area type, or turn it on for point type (on omitted: the opposite of the first object's setting, point type counting as off, or on when a gap is given). On type on a path, the layout scales the text by one factor (every character's size, leading and baseline shift; Type on a Path Options › Spacing stays) so that it fills the span between its start and end brackets, larger or smaller, and fits it again after every edit to the text, the path or the brackets; the first character's size moves in steps of 0.1 pt within 0.1 to 1,296 pt, and at 0.1 pt text that still runs past the end bracket overflows. The stored sizes keep their proportions. On area type it is Block: each line as typed (each paragraph, and each forced line break in one; lines are not broken again) is set to the frame's width, less the inset, the gutters and the paragraph's indents, by changing its font size only: its first character's size, in steps of 0.1 pt within 0.1 to 1,296 pt, the line's other characters keeping their proportions to it, with baseline shifts following. Every character's leading is its size plus lineGap (a leading change on the text, from text.setStyle, text.setRangeStyle, type.step, a character style, the Eyedropper or Text Tweaker, sets lineGap to the new leading less the size of the first character changed), and the layout sets every paragraph with wordGap as its Desired word spacing, its Minimum or Maximum moving out to wordGap when wordGap lies outside it (the paragraphs keep their own Justification… values, which apply again when Block is off; the gaps are area type's, and are kept while Block is off; a gap with no area type in the selection, and no point type it turns into area type, is an error). The sizes are written into the characters and fitted again after every edit to the text or the frame, in the same undo step; at a size limit a line can be narrower than the frame or wrap. An empty line keeps its size. Block replaces Auto Size and Shrink Text to Fit (Area Type Options › Block is the same setting). Off, the text keeps the sizes it was drawn at. Turning it on turns point type into area type with Block on, with the default Area Type Options but the gaps (options kept from an earlier frame do not carry over): the frame is as wide (along the lines) as the widest line as typed with its paragraph's indents, so that line keeps its size and sits where it was (by its own alignment), the other lines are set to that width (when negative indents take more than that line's width, the frame is as wide as the line, and Block makes it larger), and the frame then grows in depth (down, or to the left for vertical type) to hold every fitted line, around any Text Wrap objects above it; the gaps apply to it as to area type. Point type with no line to fit (empty, or only spaces and breaks) is left as it is, and so is point type when it is turned off; a selection holding type in a thread is refused (threading type turns Dynamic Text off, keeping its drawn sizes). When nothing changes, no undo step is recorded → {on, ids, fitScale (the first object's factor; 1 when off and for area type), wordGap?, lineGap? (the first area type's; left out without area type)}", + "{ids?|id?, on?: bool, wordGap?: % of a word space 0..1000 (100), lineGap?: pt -1296..1296 (0)} turn Dynamic Text on or off for the selected type on a path and area type, or turn it on for point type (on omitted: the opposite of the first object's setting, point type counting as off, or on when a gap is given). On type on a path, the layout scales the text by one factor (every character's size, leading and baseline shift; Type on a Path Options › Spacing stays) so that it fills the span between its start and end brackets, larger or smaller, and fits it again after every edit to the text, the path or the brackets; the first character's size moves in steps of 0.1 pt within 0.1 to 1,296 pt, and at 0.1 pt text that still runs past the end bracket overflows. The stored sizes keep their proportions. On area type it is Block: each line as typed (each paragraph, and each forced line break in one; lines are not broken again) is set to the frame's width, less the inset, the gutters and the paragraph's indents, by changing its font size only: its first character's size, in steps of 0.1 pt within 0.1 to 1,296 pt, the line's other characters keeping their proportions to it, with baseline shifts following. Every character's leading is its size plus lineGap (a leading change on the text, from text.setStyle, text.setRangeStyle, type.step, a character style or Text Tweaker, sets lineGap to the new leading less the size of the first character changed), and the layout sets every paragraph with wordGap as its Desired word spacing, its Minimum or Maximum moving out to wordGap when wordGap lies outside it (the paragraphs keep their own Justification… values, which apply again when Block is off; the gaps are area type's, and are kept while Block is off; a gap with no area type in the selection, and no point type it turns into area type, is an error). The sizes are written into the characters and fitted again after every edit to the text or the frame, in the same undo step; at a size limit a line can be narrower than the frame or wrap. An empty line keeps its size. Block replaces Auto Size and Shrink Text to Fit (Area Type Options › Block is the same setting). Off, the text keeps the sizes it was drawn at. Turning it on turns point type into area type with Block on, with the default Area Type Options but the gaps (options kept from an earlier frame do not carry over): the frame is as wide (along the lines) as the widest line as typed with its paragraph's indents, so that line keeps its size and sits where it was (by its own alignment), the other lines are set to that width (when negative indents take more than that line's width, the frame is as wide as the line, and Block makes it larger), and the frame then grows in depth (down, or to the left for vertical type) to hold every fitted line, around any Text Wrap objects above it; the gaps apply to it as to area type. Point type with no line to fit (empty, or only spaces and breaks) is left as it is, and so is point type when it is turned off; a selection holding type in a thread is refused (threading type turns Dynamic Text off, keeping its drawn sizes). When nothing changes, no undo step is recorded → {on, ids, fitScale (the first object's factor; 1 when off and for area type), wordGap?, lineGap? (the first area type's; left out without area type)}", has_dynamic_type, dynamic_text ), diff --git a/docs/mcp.md b/docs/mcp.md index 7a1373b938..2c579a9856 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -11329,14 +11329,14 @@ lines. The rest are VectorCraft's own rules: `text.setRangeStyle {leading}` (the Character panel's and the Properties panel's Leading field and its list), `type.step {attribute: "leading"}` (the Type tool's Alt+arrow leading steps), `charStyle.apply` with a style that sets a leading (or with `clearOverrides` when the Normal style sets one), `charStyle.edit` and `charStyle.setAttrs` when - the new definition gives its users another leading, `appearance.copyFrom` copying character attributes (the - Eyedropper) and `addon.type.textTweaker {attribute: "leading"}` (from its first changed character). `"auto"` takes - the first character's Auto leading. Every line then spreads or tightens by the change to that character's leading. - In a shaped frame where the moved lines take another size, the gap is worked out again from the new size, up to four - times, and the leading set can then differ by the last change in that size. Area Type Options and the Properties - panel show the new Line Gap. When the changed characters share one size and the gap is within its range, the Leading - field shows the leading set. Otherwise each character takes its own size plus the gap, and the field is blank where - those differ. + the new definition gives its users another leading, and `addon.type.textTweaker {attribute: "leading"}`. Text + Tweaker's ramp sets the gap from its first changed character, and every other character then takes its size plus + that gap, so the ramp does not vary the leading. `"auto"` takes the first character's Auto leading. Every line then + spreads or tightens by the change to that character's leading. The Eyedropper (`appearance.copyFrom`) copies a whole + character style, so it leaves `lineGap` as it is. In a shaped frame where the moved lines take another size, the gap + is worked out again from the new size, up to four times, and the leading set can then differ by the last change in + that size. When the changed characters share one size and the gap is within its range, the Leading field shows the + leading set. Otherwise each character takes its own size plus the gap, and the field is blank where those differ. `keepLineGap: true` on `text.setStyle` and `text.setRangeStyle` leaves `lineGap` as it is, and the Character panel's Reset Panel sends it, so a reset to Auto leading keeps the frame's Line Gap. Point type, type on a path and area type with Block off keep their own leading. diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 19083cb60f..d17a4d3b25 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1795,7 +1795,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur Type › Type on a Path › Center on Top and Center on Bottom (`type.pathCenter.top`, `type.pathCenter.bottom`, also on the Contextual Task Bar for type on a closed path) slide type on a closed path so the middle of its span lands on the path's topmost or bottommost point as drawn, keep the span's length, and set the first paragraph to Center unless it is Center or Justify Center. This is VectorCraft's own behavior (`crates/geom/src/arc.rs`, `crates/engine/src/tests/pathtype.rs`). Type on a Path Options › Align to Path (option names as in [Create type on a path](https://helpx.adobe.com/illustrator/desktop/design-with-text/edit-format-text/create-type-on-a-path.html)) moves each character by its own font, size and vertical scale: Ascender runs the top of the font's em box along the path (the ideographic em box that its `BASE` table, its typographic or `hhea` box or its ideographs give, else an em box centered on the cap height), Descender runs the bottom of the font's bounding box along it, and Center runs a line at half the height of the top of the font's H above the baseline along it. In vertical type, Ascender and Descender move the characters half an em, and Center leaves them on the path. These distances are VectorCraft's own values (`tests::on_path_align_runs_each_glyph_by_its_own_metrics`, `tests::on_path_align_finds_the_em_box_of_each_kind_of_face`, `tests::on_path_align_in_vertical_type_moves_half_an_em`). Type › Dynamic Text (`type.dynamicText`, also on the Contextual Task Bar for type on a path) sizes type on a path to fill the span between its start and end brackets and fits it again after each edit to the text or a bracket ([Dynamic Text overview](https://helpx.adobe.com/photoshop/desktop/text-typography/work-with-dynamic-text/dynamic-text-overview.html), [start and end points](https://helpx.adobe.com/photoshop/desktop/text-typography/work-with-dynamic-text/reposition-start-and-end-points.html)). VectorCraft's own rules: reshaping or scaling the path fits the text again; one factor scales every size, leading and baseline shift; the first character's size moves in 0.1 pt steps within 0.1 to 1,296 pt; turning it off, threading the type or Release Type on a Path keeps the drawn sizes; SVG, EPS, legacy `.ai` and the editing data write the drawn sizes (`crates/text/src/tests/fit.rs`, `crates/engine/src/tests/dynamic_text.rs`). - Dynamic Text on area type is Block (Type › Dynamic Text, the Contextual Task Bar, Area Type Options › Block, the Properties panel's Dynamic Text checkbox with Word Gap and Line Gap; [Dynamic Text overview](https://helpx.adobe.com/photoshop/desktop/text-typography/work-with-dynamic-text/dynamic-text-overview.html)): each line as typed is set to the frame's width by its font size, again after every edit to the text or the frame. VectorCraft's own rules: lines are not broken again, the first character's size moves in 0.1 pt steps within 0.1 to 1,296 pt, Word Gap (0 to 1,000 %, default 100) is the Desired word spacing and Line Gap (-1,296 to 1,296 pt, default 0) is added to each size for the leading, a leading change (the Character and Properties panels, the Type tool's Alt+arrow leading steps, a character style, the Eyedropper, Text Tweaker) sets Line Gap to the new leading less the size of the first character changed, Reset Panel keeps Line Gap, the sizes are written into the characters, threaded frames cannot use it, and Convert To Point Type turns it off, keeping the sizes (`crates/engine/src/cmd/typecmd/block_tests.rs`). + Dynamic Text on area type is Block (Type › Dynamic Text, the Contextual Task Bar, Area Type Options › Block, the Properties panel's Dynamic Text checkbox with Word Gap and Line Gap; [Dynamic Text overview](https://helpx.adobe.com/photoshop/desktop/text-typography/work-with-dynamic-text/dynamic-text-overview.html)): each line as typed is set to the frame's width by its font size, again after every edit to the text or the frame. VectorCraft's own rules: lines are not broken again, the first character's size moves in 0.1 pt steps within 0.1 to 1,296 pt, Word Gap (0 to 1,000 %, default 100) is the Desired word spacing and Line Gap (-1,296 to 1,296 pt, default 0) is added to each size for the leading, a leading change (the Character and Properties panels, the Type tool's Alt+arrow leading steps, a character style, Text Tweaker) sets Line Gap to the new leading less the size of the first character changed, Reset Panel keeps Line Gap, the sizes are written into the characters, threaded frames cannot use it, and Convert To Point Type turns it off, keeping the sizes (`crates/engine/src/cmd/typecmd/block_tests.rs`). Dynamic Text on point type (Type › Dynamic Text, the Contextual Task Bar; [Adjust formatting and resize text](https://helpx.adobe.com/photoshop/desktop/text-typography/work-with-dynamic-text/adjust-formatting-and-resize-text-with-dynamic-text.html) applies it to existing text) turns it into area type with Block on. VectorCraft's own rules: the frame is as wide as the widest line with its indents, so that line keeps its size and place across the page, and it grows in depth to hold every fitted line (`crates/engine/src/cmd/typecmd/block_tests.rs`). Type › Dynamic Text Presets › Circle, Arch and Bow (`type.dynamicTextPreset`) put point type or type on a path on a circular, upward-curving or downward-curving path with Dynamic Text on, with the text's position against the path (above, center, below) and its direction ([Dynamic Text overview](https://helpx.adobe.com/photoshop/desktop/text-typography/work-with-dynamic-text/dynamic-text-overview.html)). VectorCraft's own rules: the circle is as wide as the text and the text starts at its bottom; Arch and Bow are a 120° arc whose chord is as wide as the text; above, center and below are Align to Path's Descender, Center and Ascender (`crates/engine/src/tests/dynamic_text.rs`). The frames of threaded text share one Optical Margin Alignment setting: turning it on or off in one frame sets it in every frame, threading frames gives the thread its first frame's setting, and frames taken out of a thread keep it. From e7bafe3d17821dd2a8f473b5cc455c56ae360d44 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 03:29:21 -0800 Subject: [PATCH 033/151] Dynamic Text: a leading on a range inside one character leaves Line Gap text.setStyle, text.setRangeStyle and charStyle.apply style a range with both ends moved back to character boundaries, so a range inside one multibyte character styles nothing. The Line Gap now follows the same range and stays as it is when no character was styled. --- crates/engine/src/cmd/textedit.rs | 4 ++-- crates/engine/src/cmd/textstyles.rs | 2 +- crates/engine/src/cmd/typecmd.rs | 15 +++++++++++--- crates/engine/src/cmd/typecmd/block_tests.rs | 21 ++++++++++++++++++++ 4 files changed, 36 insertions(+), 6 deletions(-) diff --git a/crates/engine/src/cmd/textedit.rs b/crates/engine/src/cmd/textedit.rs index 2d6661f5aa..cf012da405 100644 --- a/crates/engine/src/cmd/textedit.rs +++ b/crates/engine/src/cmd/textedit.rs @@ -1252,8 +1252,8 @@ fn set_range_style(s: &mut Session, p: &Value) -> Result { set.extend(styled.iter().flat_map(super::fonts::run_fonts)); } // With Block on, the leading goes to the frame's line gap. - match change.leading.filter(|_| !keep_line_gap) { - Some(l) => super::typecmd::refresh_with_leading(t, a, l), + match change.leading.filter(|_| !keep_line_gap).and_then(|l| super::typecmd::styled_start(t, a, b).map(|at| (at, l))) { + Some((at, l)) => super::typecmd::refresh_with_leading(t, at, l), None => refresh_bounds(t), } n = if *f == id { t.runs.len() } else { n }; diff --git a/crates/engine/src/cmd/textstyles.rs b/crates/engine/src/cmd/textstyles.rs index 426410b661..248eb6aff7 100644 --- a/crates/engine/src/cmd/textstyles.rs +++ b/crates/engine/src/cmd/textstyles.rs @@ -1043,7 +1043,7 @@ fn apply(s: &mut Session, p: &Value, kind: Kind) -> Result { if let Some(e) = err { return Err(e); } - leading_at = (sets_leading && (a != b || len == 0)).then_some(a.min(b)); + leading_at = sets_leading.then(|| super::typecmd::styled_start(t, a.min(b), a.max(b))).flatten(); } Kind::Para => { let mut v = t.paragraph_styles(); diff --git a/crates/engine/src/cmd/typecmd.rs b/crates/engine/src/cmd/typecmd.rs index 240fb37c1f..995ec8d249 100644 --- a/crates/engine/src/cmd/typecmd.rs +++ b/crates/engine/src/cmd/typecmd.rs @@ -358,6 +358,15 @@ pub(crate) fn refresh_with_leading(t: &mut TextObject, at: usize, leading: Optio } } +/// The first character a style change over `a..b` of `t` reaches, with both ends on character +/// boundaries as [`vectorcraft_text::edit::style_range`] sets them; None when the range styles no +/// character (empty, or inside one character, in text that is not empty). +pub(crate) fn styled_start(t: &TextObject, a: usize, b: usize) -> Option { + let plain = t.plain_text(); + let (a, b) = (vectorcraft_text::edit::floor_char(&plain, a), vectorcraft_text::edit::floor_char(&plain, b)); + (a != b || plain.is_empty()).then_some(a.min(b)) +} + /// [`refresh_with_leading`] with the leading the character at `at` was just given (a character /// style, Text Tweaker). pub(crate) fn refresh_with_given_leading(t: &mut TextObject, at: usize) { @@ -1060,9 +1069,9 @@ fn set_style(s: &mut Session, p: &Value) -> Result { t.edit_paras(span, |pa| pa.justify = j); } // With Block on, the leading goes to the frame's line gap; an empty range styles nothing. - let changed = leading - .filter(|_| !keep_line_gap) - .and_then(|l| range.map_or(Some(0), |r| Some(r.bytes(t)).filter(|(a, b)| a < b).map(|(a, _)| a)).map(|at| (at, l))); + let changed = leading.filter(|_| !keep_line_gap).and_then(|l| { + range.map_or(Some(0), |r| Some(r.bytes(t)).filter(|(a, b)| a < b).and_then(|(a, b)| styled_start(t, a, b))).map(|at| (at, l)) + }); match changed { Some((at, l)) => refresh_with_leading(t, at, l), None => refresh_bounds(t), diff --git a/crates/engine/src/cmd/typecmd/block_tests.rs b/crates/engine/src/cmd/typecmd/block_tests.rs index 84d52e2cb1..e899d1e8e5 100644 --- a/crates/engine/src/cmd/typecmd/block_tests.rs +++ b/crates/engine/src/cmd/typecmd/block_tests.rs @@ -836,6 +836,27 @@ fn a_range_leading_change_with_block_on_moves_the_line_gap() { assert!(s.execute("text.setStyle", &json!({"ids": [id], "leading": 30, "keepLineGap": 1})).is_err(), "keepLineGap takes a bool"); } +/// A range inside one character styles nothing, so it leaves the line gap. +#[test] +fn a_leading_on_a_range_inside_one_character_leaves_the_line_gap() { + let mut s = session(); + let id = area(&mut s, 300.0, 400.0, "\u{e9}t\u{e9}\nsecond line"); + s.execute("type.dynamicText", &json!({"on": true})).unwrap(); + s.execute("charStyle.new", &json!({"name": "Loose", "attrs": {"leading": 50}})).unwrap(); + let gap = text(&s, id).area.line_gap; + let range = json!({"start": 0, "end": 1}); + let mut setstyle = json!({"ids": [id], "leading": 50}); + let mut setrange = json!({"id": id, "leading": 50}); + let mut apply = json!({"name": "Loose", "id": id}); + for p in [&mut setstyle, &mut setrange, &mut apply] { + p.as_object_mut().unwrap().extend(range.as_object().unwrap().clone()); + } + for (c, p) in [("text.setStyle", setstyle), ("text.setRangeStyle", setrange), ("charStyle.apply", apply)] { + s.execute(c, &p).unwrap_or_else(|e| panic!("{c}: {e}")); + assert_eq!(text(&s, id).area.line_gap, gap, "{c}"); + } +} + /// `type.step {attribute: "leading"}` (Alt+Up/Down) on Block text moves the line gap by the step. #[test] fn a_leading_step_with_block_on_moves_the_line_gap() { From bb1da3771deeeea142bf4094fe9a457383929b4f Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 12:24:50 -0800 Subject: [PATCH 034/151] Scripts: tags on page items and documents PageItem.tags and Document.tags give scripts the Tags and Tag objects the scripting reference describes: name and value pairs on a page item, read, added, renamed and deleted through the new object.tags, object.tag.add, object.tag.set, object.tag.remove and object.tag.removeAll commands, each one undo step. The native file keeps the tags and their ids. On opening, each object keeps its first 64 tags whose name and value are at most 65,536 bytes, and a tag whose id is missing, out of range or repeated gets a new one. A deleted tag's id is not given out again, so a script's Tag for it throws "Stale tag". The undo history's memory estimate now counts the text an object's attributes hold (note, URL, data, events, classes, foreign attributes and tags). --- crates/doc/src/lib.rs | 2 +- crates/doc/src/mem.rs | 32 ++ crates/doc/src/node.rs | 2 +- crates/doc/src/node/attributes.rs | 128 ++++++++ crates/engine/src/cmd.rs | 2 + crates/engine/src/cmd/plugin_call/reviewed.rs | 5 + crates/engine/src/cmd/tags.rs | 191 +++++++++++ crates/engine/src/script/dom.rs | 6 +- crates/engine/src/script/dom/tags.rs | 306 ++++++++++++++++++ crates/engine/src/tests.rs | 1 + crates/engine/src/tests/script_tags.rs | 255 +++++++++++++++ .../tests/it/script_host_vs_scriptcheck.rs | 12 +- crates/format/src/lib.rs | 3 + docs/mcp.md | 20 ++ docs/target-app-parity.md | 1 + 15 files changed, 959 insertions(+), 7 deletions(-) create mode 100644 crates/engine/src/cmd/tags.rs create mode 100644 crates/engine/src/script/dom/tags.rs create mode 100644 crates/engine/src/tests/script_tags.rs diff --git a/crates/doc/src/lib.rs b/crates/doc/src/lib.rs index 5a9b27b304..b9e0f4e9a3 100644 --- a/crates/doc/src/lib.rs +++ b/crates/doc/src/lib.rs @@ -116,7 +116,7 @@ pub use metadata::{CopyrightStatus, DocMetadata}; pub use node::Knockout; pub use node::Scaling; pub use node::{Extras, ExtrasMut, ImageObject, LAYER_COLORS, LayerColor, LiveShape, Node, NodeExtras, NodeId, NodeKind, OpacityMask}; -pub use node::{ForeignAttribute, ImageMap, MAX_SVG_SCRIPTS, ObjectAttributes, SVG_EVENTS}; +pub use node::{ForeignAttribute, ImageMap, MAX_SVG_SCRIPTS, MAX_TAG_TEXT, MAX_TAGS, ObjectAttributes, ObjectTag, SVG_EVENTS}; pub use orient::OrientedBox; pub use pattern::{Overlap, PatternDef, PatternEdit, RepeatKind, RepeatSpec, TileType}; pub use perspective::PerspectiveAttachment; diff --git a/crates/doc/src/mem.rs b/crates/doc/src/mem.rs index 3519986512..a1bfaefe7d 100644 --- a/crates/doc/src/mem.rs +++ b/crates/doc/src/mem.rs @@ -278,6 +278,7 @@ fn node_bytes(n: &Node, other: Option<&Node>, counted: &mut HashSet) -> u if let Some(e) = n.extras_box() { b += ALLOC + size_of::(); b += boxed(&e.mask) + boxed(&e.graph) + boxed(&e.shaper) + boxed(&e.attrs) + boxed(&e.slice) + boxed(&e.perspective); + b += e.attrs.as_deref().map_or(0, attrs_bytes); b += boxed(&e.dimension) + boxed(&e.live_paint_gaps) + boxed(&e.colorize); b += e .color_mask @@ -404,6 +405,22 @@ fn swatches_bytes(s: &[Swatch]) -> usize { ALLOC + std::mem::size_of_val(s) + s.iter().map(|w| w.name.capacity() + paint_heap_bytes(&w.paint)).sum::() } +/// The heap an object's attributes own: their text, data, events, classes, foreign attributes and +/// tags. +fn attrs_bytes(a: &crate::ObjectAttributes) -> usize { + let pairs = |v: &Vec<(String, String)>| vec_bytes(v) + v.iter().map(|(k, v)| k.capacity() + v.capacity()).sum::(); + a.url.capacity() + + a.note.capacity() + + pairs(&a.data) + + pairs(&a.events) + + vec_bytes(&a.classes) + + a.classes.iter().map(String::capacity).sum::() + + vec_bytes(&a.foreign) + + a.foreign.iter().map(|f| f.ns.capacity() + f.prefix.capacity() + f.name.capacity() + f.value.capacity()).sum::() + + vec_bytes(&a.tags) + + a.tags.iter().map(|t| t.name.capacity() + t.value.capacity()).sum::() +} + /// A vector's buffer (not what its elements own). fn vec_bytes(v: &Vec) -> usize { if v.capacity() == 0 { 0 } else { ALLOC + v.capacity() * size_of::() } @@ -490,6 +507,21 @@ mod tests { assert!((400..1200).contains(&per), "{per} bytes per moved rectangle"); } + /// An object's attributes count with their text: a version of a rectangle with a long tag and + /// a long note keeps both. + #[test] + fn tags_and_notes_count() { + let before = doc_with_rects(1); + let mut after = before.clone(); + let id = after.layers[0].children().unwrap()[0].id; + after.node_mut(id).unwrap().edit_attrs(|a| { + a.note = "n".repeat(30_000); + a.tags.push(crate::ObjectTag { id: 1, name: "size".into(), value: "v".repeat(60_000) }); + }); + let bytes = after.retained_bytes(&before); + assert!(bytes >= 90_000, "{bytes} bytes for a rectangle with 90,000 bytes of attributes"); + } + #[test] fn a_grouped_object_is_found_shared() { let before = doc_with_rects(100); diff --git a/crates/doc/src/node.rs b/crates/doc/src/node.rs index 79ce594212..87b9a375db 100644 --- a/crates/doc/src/node.rs +++ b/crates/doc/src/node.rs @@ -24,7 +24,7 @@ mod opacity; mod ops; mod wire; -pub use attributes::{ForeignAttribute, ImageMap, MAX_SVG_SCRIPTS, ObjectAttributes, SVG_EVENTS}; +pub use attributes::{ForeignAttribute, ImageMap, MAX_SVG_SCRIPTS, MAX_TAG_TEXT, MAX_TAGS, ObjectAttributes, ObjectTag, SVG_EVENTS}; pub use clip::{ClipPaint, Uniter}; pub use extras::{Extras, ExtrasMut, NodeExtras}; pub use ids::{LAYER_COLORS, LayerColor, NodeId}; diff --git a/crates/doc/src/node/attributes.rs b/crates/doc/src/node/attributes.rs index 6f573a61aa..dca575c6f6 100644 --- a/crates/doc/src/node/attributes.rs +++ b/crates/doc/src/node/attributes.rs @@ -38,6 +38,134 @@ pub struct ObjectAttributes { /// with it. #[serde(default, skip_serializing_if = "Vec::is_empty")] pub foreign: Vec, + /// The object's tags, in order: name and value pairs that scripts read and write + /// (`object.tag.add`). Names may be empty or repeated. At most [`MAX_TAGS`], each name and + /// value at most [`MAX_TAG_TEXT`] bytes. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub tags: Vec, +} + +/// The most tags one object has. +pub const MAX_TAGS: usize = 64; + +/// The longest name or value a tag has, in bytes. +pub const MAX_TAG_TEXT: usize = 64 * 1024; + +/// A tag on an object: a name and a value, with an id that tells it apart from the object's other +/// tags while its name and value change. +#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +pub struct ObjectTag { + /// Distinct among the object's tags: a new tag takes an id from + /// [`crate::Document::alloc_tag_id`], and deleting a tag raises the next node id above its id, + /// so a deleted tag's id is not given out again. + #[serde(default)] + pub id: u64, + #[serde(default)] + pub name: String, + #[serde(default)] + pub value: String, +} + +impl ObjectAttributes { + /// Keeps the tags within the limits: the first [`MAX_TAGS`] whose name and value are at most + /// [`MAX_TAG_TEXT`] bytes. → whether any was dropped. + pub fn tidy_tags(&mut self) -> bool { + let before = self.tags.len(); + self.tags.retain(|t| t.name.len() <= MAX_TAG_TEXT && t.value.len() <= MAX_TAG_TEXT); + self.tags.truncate(MAX_TAGS); + self.tags.len() != before + } +} + +impl crate::Document { + /// Keeps every object's tags within the limits ([`ObjectAttributes::tidy_tags`]) in the art of + /// the layers, symbols, graph designs and pattern swatches (opacity-mask art included). A tag + /// keeps its id when the id is from 1 to below [`crate::limits::MAX_NEXT_ID`] and no earlier + /// tag of the object has it. Every other tag gets a new id: from the next node id on, above + /// every kept id, when those ids stay below that limit; otherwise the smallest id the object's + /// other tags do not have. The next node id is then raised past every tag id below the limit. + /// It recurses through the art: call it on a document no deeper than + /// [`crate::depth::MAX_DEPTH`]. + pub fn tidy_tags(&mut self) { + fn keeps(t: &ObjectTag, earlier: &[ObjectTag]) -> bool { + (1..crate::limits::MAX_NEXT_ID).contains(&t.id) && !earlier.iter().any(|o| o.id == t.id) + } + // The limits, the largest kept id and the number of new ids first, so that a new id never + // meets a kept one. + let mut next = self.peek_next_id(); + let mut fresh = 0u64; + self.each_tagged(&mut |a| { + a.tidy_tags(); + for (i, t) in a.tags.iter().enumerate() { + if keeps(t, &a.tags[..i]) { + next = next.max(t.id.saturating_add(1)); + } else { + fresh = fresh.saturating_add(1); + } + } + }); + if fresh == 0 { + self.raise_next_id(next); + return; + } + let in_range = next.saturating_add(fresh) <= crate::limits::MAX_NEXT_ID; + self.each_tagged(&mut |a| { + let kept: Vec = (0..a.tags.len()).map(|i| keeps(&a.tags[i], &a.tags[..i])).collect(); + let mut used: Vec = a.tags.iter().zip(&kept).filter(|(_, k)| **k).map(|(t, _)| t.id).collect(); + for (i, k) in kept.iter().enumerate() { + if *k { + continue; + } + let id = if in_range { + next = next.saturating_add(1); + next - 1 + } else { + (1..).find(|c| !used.contains(c)).unwrap_or(1) + }; + a.tags[i].id = id; + used.push(id); + } + }); + self.raise_next_id(next); + } + + /// A new tag id for object `id`, which none of its tags has: the next node id. `None` once the + /// next node id has reached [`crate::limits::MAX_NEXT_ID`] (a file with ids at the top of the + /// range), since an id from there would be outside the range [`Self::tidy_tags`] keeps and an + /// id below it could be a deleted tag's. + pub fn alloc_tag_id(&mut self, id: crate::NodeId) -> Option { + let used: Vec = + self.node(id).map(|n| n.extras().attrs.as_deref().map_or(Vec::new(), |a| a.tags.iter().map(|t| t.id).collect())).unwrap_or_default(); + for _ in 0..=used.len() { + if self.peek_next_id() >= crate::limits::MAX_NEXT_ID { + return None; + } + let tag = self.alloc_id().0; + if !used.contains(&tag) { + return Some(tag); + } + } + None + } + + /// Calls `f` with the attributes of every object with tags in the art [`Self::tidy_tags`] reads. + fn each_tagged(&mut self, f: &mut impl FnMut(&mut ObjectAttributes)) { + let mut fix = |n: &mut Node| { + if n.extras().attrs.as_deref().is_some_and(|a| !a.tags.is_empty()) { + n.edit_attrs(&mut *f); + } + }; + let roots = self + .layers + .iter_mut() + .chain(self.symbols.iter_mut().map(|s| &mut s.art)) + .chain(self.graph_designs.iter_mut().map(|g| &mut g.art)) + .chain(self.patterns.iter_mut().flat_map(|p| p.art.iter_mut())) + .chain(self.pattern_edit.iter_mut().filter_map(|pe| pe.original.as_mut()).flat_map(|p| p.art.iter_mut())); + for root in roots { + crate::placed_document::each_mut(std::sync::Arc::make_mut(root), &mut fix); + } + } } /// An attribute in another application's XML namespace: `plotter:pen="2"` with `xmlns:plotter= diff --git a/crates/engine/src/cmd.rs b/crates/engine/src/cmd.rs index 4f0d2bad63..7015093754 100644 --- a/crates/engine/src/cmd.rs +++ b/crates/engine/src/cmd.rs @@ -101,6 +101,7 @@ pub mod swatchlib; pub(crate) mod symboledit; pub mod symbollib; pub(crate) mod tabs; +pub(crate) mod tags; mod textedit; pub use textedit::effective_kerning; @@ -375,6 +376,7 @@ pub fn command_specs() -> &'static [CommandSpec] { v.extend(library::specs()); v.extend(expand::specs()); v.extend(attributes::specs()); + v.extend(tags::specs()); v.extend(interactivity::specs()); v.extend(spelling::specs()); v.extend(svgfilter::specs()); diff --git a/crates/engine/src/cmd/plugin_call/reviewed.rs b/crates/engine/src/cmd/plugin_call/reviewed.rs index 4542b6b864..b835403d7e 100644 --- a/crates/engine/src/cmd/plugin_call/reviewed.rs +++ b/crates/engine/src/cmd/plugin_call/reviewed.rs @@ -401,6 +401,11 @@ pub(super) const ALLOWED: &[&str] = &[ "object.slice.release", "object.slice.select", "object.slice.setRect", + "object.tag.add", + "object.tag.remove", + "object.tag.removeAll", + "object.tag.set", + "object.tags", "object.textWrap.make", "object.textWrap.options", "object.textWrap.release", diff --git a/crates/engine/src/cmd/tags.rs b/crates/engine/src/cmd/tags.rs new file mode 100644 index 0000000000..8707e7dc1e --- /dev/null +++ b/crates/engine/src/cmd/tags.rs @@ -0,0 +1,191 @@ +//! An object's tags: name and value pairs scripts keep on page items (`object.tags`, +//! `object.tag.add`, `object.tag.set`, `object.tag.remove`, `object.tag.removeAll`). The native file +//! keeps them; other formats do not write them. + +use std::collections::BTreeSet; + +use serde_json::{Value, json}; +use vectorcraft_doc::{Document, MAX_TAG_TEXT, MAX_TAGS, Node, ObjectTag}; + +use super::{CommandSpec, NodeId, Result, Session, bad, cmd, has_doc, ids_param, targets, text_param, u64_req}; + +pub fn specs() -> Vec { + vec![ + cmd!( + query "object.tags", + "Attributes", + [], + None, + "{id} → {tags: [{tag, name, value}]} the object's tags in order; `tag` tells each apart from the others while its name and value change", + has_doc, + list + ), + cmd!( + "object.tag.add", + "Attributes", + [], + None, + "{id, name?: string, value?: string} adds a tag after the object's others (\"\" for a name or value left out), as one undo step; an object has at most 64 tags, each name and value at most 65,536 bytes → {tag}", + has_doc, + add + ), + cmd!( + "object.tag.set", + "Attributes", + [], + None, + "{id, tag, name?: string, value?: string} changes the tag's name or value, as one undo step; a value it already has changes nothing → {changed: bool}", + has_doc, + set + ), + cmd!("object.tag.remove", "Attributes", [], None, "{id, tag} deletes the tag, as one undo step → {}", has_doc, remove), + cmd!( + "object.tag.removeAll", + "Attributes", + [], + None, + "{ids?|id?} deletes every tag of the objects in ids or the selection, as one undo step → {changed: objects}", + has_doc, + remove_all + ), + ] +} + +/// The page item `p`'s `id` names: an object of the document, not a layer or a ruler guide. +fn object(s: &Session, p: &Value, c: &str) -> Result { + let id = NodeId(u64_req(p, "id", c)?); + let d = &s.doc()?.doc; + match d.node(id) { + Some(n) if is_page_item(n) => Ok(id), + Some(_) => Err(bad(c, format!("object {} is a layer or a ruler guide, which has no tags", id.0))), + None => Err(bad(c, format!("no object {}", id.0))), + } +} + +fn is_page_item(n: &Node) -> bool { + !matches!(n.kind, vectorcraft_doc::NodeKind::Layer { .. }) && !n.is_ruler_guide() +} + +/// The tags of `n`. +pub(crate) fn tags_of(n: &Node) -> &[ObjectTag] { + n.extras().attrs.as_deref().map_or(&[], |a| a.tags.as_slice()) +} + +/// The tag `p`'s `tag` names on object `id`: its index among the object's tags. +fn tag_index(d: &Document, id: NodeId, p: &Value, c: &str) -> Result { + let tag = u64_req(p, "tag", c)?; + let n = d.node(id).ok_or_else(|| bad(c, format!("no object {}", id.0)))?; + tags_of(n).iter().position(|t| t.id == tag).ok_or_else(|| bad(c, format!("object {} has no tag {tag}", id.0))) +} + +/// The text `p` gives for `key` (a tag's name or value), at most [`MAX_TAG_TEXT`] bytes. +fn tag_text<'a>(p: &'a Value, key: &str, c: &str) -> Result> { + let t = text_param(p, key, c)?; + if t.is_some_and(|t| t.len() > MAX_TAG_TEXT) { + return Err(bad(c, format!("a tag's {key} is longer than 65,536 bytes"))); + } + Ok(t) +} + +fn list(s: &mut Session, p: &Value) -> Result { + const C: &str = "object.tags"; + let id = object(s, p, C)?; + let d = &s.doc()?.doc; + let tags = d.node(id).map(tags_of).unwrap_or_default(); + Ok(json!({"tags": tags.iter().map(|t| json!({"tag": t.id, "name": t.name, "value": t.value})).collect::>()})) +} + +fn add(s: &mut Session, p: &Value) -> Result { + const C: &str = "object.tag.add"; + let id = object(s, p, C)?; + let name = tag_text(p, "name", C)?.unwrap_or_default().to_string(); + let value = tag_text(p, "value", C)?.unwrap_or_default().to_string(); + let count = s.doc()?.doc.node(id).map_or(0, |n| tags_of(n).len()); + if count >= MAX_TAGS { + return Err(bad(C, format!("object {} has 64 tags, the most an object has", id.0))); + } + let tag = s.edit("Attributes", |d, _| { + // A document-wide id: a tag deleted earlier in the run never shares it. + let tag = d.alloc_tag_id(id).ok_or_else(|| bad(C, "the document has no tag ids left"))?; + let n = d.node_mut(id).ok_or_else(|| bad(C, format!("no object {}", id.0)))?; + n.edit_attrs(|a| a.tags.push(ObjectTag { id: tag, name, value })); + Ok(tag) + })?; + Ok(json!({"tag": tag})) +} + +fn set(s: &mut Session, p: &Value) -> Result { + const C: &str = "object.tag.set"; + let id = object(s, p, C)?; + let name = tag_text(p, "name", C)?; + let value = tag_text(p, "value", C)?; + if name.is_none() && value.is_none() { + return Err(bad(C, "give name or value")); + } + let at = tag_index(&s.doc()?.doc, id, p, C)?; + let same = s + .doc()? + .doc + .node(id) + .and_then(|n| tags_of(n).get(at)) + .is_some_and(|t| name.is_none_or(|v| t.name == v) && value.is_none_or(|v| t.value == v)); + if same { + return Ok(json!({"changed": false})); + } + s.edit("Attributes", |d, _| { + let n = d.node_mut(id).ok_or_else(|| bad(C, format!("no object {}", id.0)))?; + n.edit_attrs(|a| { + if let Some(t) = a.tags.get_mut(at) { + if let Some(v) = name { + v.clone_into(&mut t.name); + } + if let Some(v) = value { + v.clone_into(&mut t.value); + } + } + }); + Ok(()) + })?; + Ok(json!({"changed": true})) +} + +fn remove(s: &mut Session, p: &Value) -> Result { + const C: &str = "object.tag.remove"; + let id = object(s, p, C)?; + let at = tag_index(&s.doc()?.doc, id, p, C)?; + s.edit("Attributes", |d, _| { + let n = d.node_mut(id).ok_or_else(|| bad(C, format!("no object {}", id.0)))?; + let gone = n.edit_attrs(|a| (at < a.tags.len()).then(|| a.tags.remove(at).id)); + if let Some(t) = gone { + d.raise_next_id(t.saturating_add(1)); + } + Ok(()) + })?; + Ok(json!({})) +} + +fn remove_all(s: &mut Session, p: &Value) -> Result { + const C: &str = "object.tag.removeAll"; + ids_param(p, "ids", C)?; + let ids = targets(s, p)?; + let d = &s.doc()?.doc; + for id in &ids { + if d.node(*id).is_none() { + return Err(bad(C, format!("no object {}", id.0))); + } + } + let tagged: BTreeSet = ids.into_iter().filter(|id| d.node(*id).is_some_and(|n| !tags_of(n).is_empty())).collect(); + if !tagged.is_empty() { + s.edit("Attributes", |d, _| { + let mut last = 0; + for id in &tagged { + if let Some(n) = d.node_mut(*id) { + last = n.edit_attrs(|a| a.tags.drain(..).map(|t| t.id).fold(last, u64::max)); + } + } + d.raise_next_id(last.saturating_add(1)); + Ok(()) + })?; + } + Ok(json!({"changed": tagged.len()})) +} diff --git a/crates/engine/src/script/dom.rs b/crates/engine/src/script/dom.rs index 241720f786..e0deca741e 100644 --- a/crates/engine/src/script/dom.rs +++ b/crates/engine/src/script/dom.rs @@ -38,6 +38,8 @@ use vectorcraft_js::{Data, HostClass, HostError, HostFunction, HostItem, HostMem use super::{HISTORY_LOST, Host, Link, Savepoint, command, command_value, current, data_size}; use crate::{DocState, Document, NodeId, NodeKind, Session}; +mod tags; + /// The error for a member read or called with no document open. pub const NO_ACTIVE_DOCUMENT: &str = "No active document"; /// The error for an object that was deleted, or that came from an earlier run. @@ -1765,6 +1767,7 @@ pub(super) fn install(realm: &mut Realm, link: &Link) -> std::result::Result<(), .into_iter() .map(|m| later(l, "Document", m)), ); + document.push(("tags".into(), get(l, tags::doc_tags))); classes.push(class("Document", None, document, None)); classes.push(class( "PageItems", @@ -1784,6 +1787,7 @@ pub(super) fn install(realm: &mut Realm, link: &Link) -> std::result::Result<(), ("parent", get(l, item_parent)), ("name", property(l, item_name, item_set_name)), ("note", property(l, item_note, item_set_note)), + ("tags", get(l, tags::item_tags)), ("hidden", property(l, item_hidden, item_set_hidden)), ("locked", property(l, item_locked, item_set_locked)), ("selected", property(l, item_selected, item_set_selected)), @@ -1811,7 +1815,6 @@ pub(super) fn install(realm: &mut Realm, link: &Link) -> std::result::Result<(), "layer", "pixelAligned", "sliced", - "tags", "uRL", "uuid", "visibilityVariable", @@ -1830,6 +1833,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.push(class("Layer", None, named(vec![("typename", get(l, layer_typename)), ("name", get(l, layer_name))]), None)); + classes.extend(tags::classes(l)); realm.define_host_classes(classes, vec![("app".into(), host_ref("Application", &[]))]) } diff --git a/crates/engine/src/script/dom/tags.rs b/crates/engine/src/script/dom/tags.rs new file mode 100644 index 0000000000..c62f5eae81 --- /dev/null +++ b/crates/engine/src/script/dom/tags.rs @@ -0,0 +1,306 @@ +//! `PageItem.tags`, `Document.tags` and the `Tag` objects in them, as the help pages +//! and +//! describe them: name and value pairs on a +//! page item, which the native file keeps. Each change runs one of the `object.tag.*` commands. +//! +//! VectorCraft's own rules, which the help pages do not state: +//! - A `Tags` collection is live: it lists the tags in their order on the object, counted from 0. +//! `Document.tags` lists the tags of every page item, in the order `pageItems` lists the items, +//! and cannot add a tag, since a tag belongs to a page item. +//! - `add()` gives a tag with an empty name and value. Names may be empty or repeated, and +//! `getByName` gives the first tag with the name. +//! - `name` and `value` are strings of at most 65,536 bytes, and an object has at most 64 tags. +//! - A tag that was deleted, or whose page item was, throws an error on every member. + +use std::ops::ControlFlow; + +use vectorcraft_doc::{MAX_TAG_TEXT, ObjectTag}; + +use super::{ + Answer, Doc, Host, Item, Link, NOT_FOUND, STALE_DOCUMENT, STALE_ITEM, arg, class, command, doc_of, doc_ref, edit_item, find_doc, float, get, + handle_of, id_of, id_parts, item_of, item_ref, method, named, num, on_doc, page_items, property, text, typename, whole, with_doc, +}; +use crate::NodeId; +use serde_json::json; +use vectorcraft_js::{Data, HostClass, HostError, HostMember, host_ref}; + +/// The error for a tag that was deleted, or that came from an earlier run. +pub const STALE_TAG: &str = "Stale tag"; +/// The error of `Document.tags.add()`. +pub const NO_OWNER: &str = "A tag is added to a page item's tags, not to the document's"; + +/// What a `Tags` collection lists the tags of. +#[derive(Clone, Copy)] +enum Owner { + Item(Item), + Doc(Doc), +} + +/// The owner of the `Tags` collection `d` names. +fn owner_of(h: &Host, d: &Data) -> std::result::Result { + let Some(handle) = handle_of(d, "Tags") else { return Err(HostError::Type("this is not a Tags collection".into())) }; + match handle.as_slice() { + [run, uid] => find_doc(h, *run, *uid).map(Owner::Doc).ok_or_else(|| HostError::Error(STALE_DOCUMENT.into())), + [run, uid, high, low] => Ok(Owner::Item(resolve_item(h, *run, *uid, *high, *low)?)), + _ => Err(HostError::Type("this is not a Tags collection".into())), + } +} + +/// The page item a handle's run, document uid and id (as [`id_parts`] gave it) name, which must +/// still be in its document. +fn resolve_item(h: &Host, run: f64, uid: f64, high: f64, low: f64) -> std::result::Result { + let doc = find_doc(h, run, uid).ok_or_else(|| HostError::Error(STALE_ITEM.into()))?; + let id = id_of(high, low).ok_or_else(|| HostError::Error(STALE_ITEM.into()))?; + let alive = with_doc(h, doc, |_, st| st.doc.node(id).is_some_and(|n| typename(n).is_some())); + if !alive { + return Err(HostError::Error(STALE_ITEM.into())); + } + Ok(Item { doc, id }) +} + +/// Calls `f` with each tag `owner` lists, in order, and the page item it is on, until `f` breaks. +/// The tags are borrowed from the document, not copied. `Document.tags` charges the run by the +/// number of page items read. +fn each(h: &Host, owner: Owner, mut f: impl FnMut(NodeId, &ObjectTag) -> ControlFlow<()>) -> std::result::Result<(), HostError> { + match owner { + Owner::Item(item) => with_doc(h, item.doc, |_, st| { + if let Some(n) = st.doc.node(item.id) { + for t in crate::cmd::tags::tags_of(n) { + if f(item.id, t).is_break() { + break; + } + } + } + Ok(()) + }), + Owner::Doc(doc) => with_doc(h, doc, |_, st| { + let ids = page_items(h, st); + h.charge_call(ids.len() as u64)?; + for id in ids.iter() { + if let Some(n) = st.doc.node(*id) { + for t in crate::cmd::tags::tags_of(n) { + if f(*id, t).is_break() { + return Ok(()); + } + } + } + } + Ok(()) + }), + } +} + +/// The first tag `owner` lists for which `pick` holds: its page item and its id. +fn find(h: &Host, owner: Owner, mut pick: impl FnMut(&ObjectTag) -> bool) -> std::result::Result, HostError> { + let mut found = None; + each(h, owner, |id, t| { + if pick(t) { + found = Some((id, t.id)); + return ControlFlow::Break(()); + } + ControlFlow::Continue(()) + })?; + Ok(found) +} + +fn doc_of_owner(owner: Owner) -> Doc { + match owner { + Owner::Item(i) => i.doc, + Owner::Doc(d) => d, + } +} + +fn tag_ref(h: &Host, doc: Doc, id: NodeId, tag: u64) -> Data { + let [high, low] = id_parts(id); + let [tag_high, tag_low] = id_parts(NodeId(tag)); + host_ref("Tag", &[float(h.run), float(doc.uid), high, low, tag_high, tag_low]) +} + +/// `PageItem.tags`. +pub(super) fn item_tags(h: &Host, a: &[Data]) -> Answer { + let item = item_of(h, arg(a, 0))?; + let [high, low] = id_parts(item.id); + Ok(host_ref("Tags", &[float(h.run), float(item.doc.uid), high, low])) +} + +/// `Document.tags`. +pub(super) fn doc_tags(h: &Host, a: &[Data]) -> Answer { + let doc = doc_of(h, arg(a, 0), "Document")?; + Ok(host_ref("Tags", &[float(h.run), float(doc.uid)])) +} + +// ---- Tags ---- + +fn tags_length(h: &Host, a: &[Data]) -> Answer { + let owner = owner_of(h, arg(a, 0))?; + let mut count = 0u64; + each(h, owner, |_, _| { + count += 1; + ControlFlow::Continue(()) + })?; + Ok(num(float(count))) +} + +fn tags_parent(h: &Host, a: &[Data]) -> Answer { + match owner_of(h, arg(a, 0))? { + Owner::Item(item) => Ok(with_doc(h, item.doc, |_, st| item_ref(h, st, item.id))), + Owner::Doc(doc) => Ok(doc_ref(h, doc.uid)), + } +} + +fn tags_at(h: &Host, a: &[Data]) -> Answer { + let owner = owner_of(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) }; + let mut left = i; + let found = find(h, owner, |_| { + let here = left == 0; + left = left.wrapping_sub(1); + here + })?; + Ok(found.map_or(Data::Undefined, |(id, tag)| tag_ref(h, doc_of_owner(owner), id, tag))) +} + +fn tags_by_name(h: &Host, a: &[Data]) -> Answer { + let owner = owner_of(h, arg(a, 0))?; + let Data::String(name) = arg(a, 1) else { return Err(HostError::Type("give a name, as a string".into())) }; + let found = find(h, owner, |t| t.name == *name)?; + found.map(|(id, tag)| tag_ref(h, doc_of_owner(owner), id, tag)).ok_or_else(|| HostError::Error(NOT_FOUND.into())) +} + +fn tags_index(h: &Host, a: &[Data]) -> Answer { + match arg(a, 1) { + Data::String(_) => tags_by_name(h, a), + Data::Number(_) => match tags_at(h, a)? { + Data::Undefined => Err(HostError::Error(NOT_FOUND.into())), + d => Ok(d), + }, + _ => Err(HostError::Type("give a name or an index".into())), + } +} + +/// `tags.add()`: a new tag with an empty name and value after the item's other tags. +fn tags_add(h: &Host, a: &[Data]) -> Answer { + let item = match owner_of(h, arg(a, 0))? { + Owner::Item(item) => item, + Owner::Doc(_) => return Err(HostError::Error(NO_OWNER.into())), + }; + edit_item(h, item, "object.tag.add", &json!({"id": item.id.0}))?; + // The new tag is the item's last. Its id is read from the document, since the command's answer + // gives it as a number, which is exact only up to 2^53. + let tag = with_doc(h, item.doc, |_, st| st.doc.node(item.id).and_then(|n| crate::cmd::tags::tags_of(n).last().map(|t| t.id))); + let tag = tag.ok_or_else(|| HostError::Error("the tag was not added".into()))?; + Ok(tag_ref(h, item.doc, item.id, tag)) +} + +/// `tags.removeAll()`: deletes every tag in the collection, in one command. +fn tags_remove_all(h: &Host, a: &[Data]) -> Answer { + let owner = owner_of(h, arg(a, 0))?; + let mut ids: Vec = Vec::new(); + each(h, owner, |id, _| { + if ids.last() != Some(&id.0) { + ids.push(id.0); + } + ControlFlow::Continue(()) + })?; + if !ids.is_empty() { + let doc = doc_of_owner(owner); + on_doc(h, doc.uid, true, |h| command(h, "object.tag.removeAll", &json!({"ids": ids})))?; + } + Ok(Data::Undefined) +} + +// ---- Tag ---- + +/// A tag: its page item and its id there. +#[derive(Clone, Copy)] +struct TagRef { + item: Item, + tag: u64, +} + +/// The tag `d` names, which must still be on its page item. +fn tag_of(h: &Host, d: &Data) -> std::result::Result<(TagRef, ObjectTag), HostError> { + let Some(handle) = handle_of(d, "Tag") else { return Err(HostError::Type("this is not a Tag".into())) }; + let [run, uid, high, low, tag_high, tag_low] = handle.as_slice() else { return Err(HostError::Type("this is not a Tag".into())) }; + let item = resolve_item(h, *run, *uid, *high, *low)?; + let tag = id_of(*tag_high, *tag_low).ok_or_else(|| HostError::Error(STALE_TAG.into()))?.0; + let found = with_doc(h, item.doc, |_, st| st.doc.node(item.id).and_then(|n| crate::cmd::tags::tags_of(n).iter().find(|t| t.id == tag).cloned())); + let t = found.ok_or_else(|| HostError::Error(STALE_TAG.into()))?; + Ok((TagRef { item, tag }, t)) +} + +fn tag_name(h: &Host, a: &[Data]) -> Answer { + Ok(text(tag_of(h, arg(a, 0))?.1.name)) +} + +fn tag_value(h: &Host, a: &[Data]) -> Answer { + Ok(text(tag_of(h, arg(a, 0))?.1.value)) +} + +/// Sets the tag's `key` (`name` or `value`) to the string the script gives, with no command when +/// it already has it. +fn set_text(h: &Host, a: &[Data], key: &str) -> Answer { + let Data::String(v) = arg(a, 1) else { return Err(HostError::Type(format!("{key} must be a string"))) }; + if v.len() > MAX_TAG_TEXT { + return Err(HostError::Range(format!("a tag's {key} is longer than 65,536 bytes"))); + } + let (t, now) = tag_of(h, arg(a, 0))?; + let same = if key == "name" { now.name == *v } else { now.value == *v }; + if !same { + edit_item(h, t.item, "object.tag.set", &json!({"id": t.item.id.0, "tag": t.tag, key: v}))?; + } + Ok(Data::Undefined) +} + +fn tag_set_name(h: &Host, a: &[Data]) -> Answer { + set_text(h, a, "name") +} + +fn tag_set_value(h: &Host, a: &[Data]) -> Answer { + set_text(h, a, "value") +} + +fn tag_parent(h: &Host, a: &[Data]) -> Answer { + let (t, _) = tag_of(h, arg(a, 0))?; + Ok(with_doc(h, t.item.doc, |_, st| item_ref(h, st, t.item.id))) +} + +fn tag_remove(h: &Host, a: &[Data]) -> Answer { + let (t, _) = tag_of(h, arg(a, 0))?; + edit_item(h, t.item, "object.tag.remove", &json!({"id": t.item.id.0, "tag": t.tag}))?; + Ok(Data::Undefined) +} + +/// `Tags.typename`, which throws like every other member once the collection's owner is gone. +fn tags_typename(h: &Host, a: &[Data]) -> Answer { + owner_of(h, arg(a, 0))?; + Ok(text("Tags")) +} + +/// `Tag.typename`, which throws like every other member once the tag is gone. +fn tag_typename(h: &Host, a: &[Data]) -> Answer { + tag_of(h, arg(a, 0))?; + Ok(text("Tag")) +} + +/// The `Tags` and `Tag` classes. +pub(super) fn classes(l: &Link) -> Vec { + let tags: Vec<(String, HostMember)> = named(vec![ + ("typename", get(l, tags_typename)), + ("length", get(l, tags_length)), + ("parent", get(l, tags_parent)), + ("index", method(l, tags_index)), + ("getByName", method(l, tags_by_name)), + ("add", method(l, tags_add)), + ("removeAll", method(l, tags_remove_all)), + ]); + let tag = named(vec![ + ("typename", get(l, tag_typename)), + ("name", property(l, tag_name, tag_set_name)), + ("value", property(l, tag_value, tag_set_value)), + ("parent", get(l, tag_parent)), + ("remove", method(l, tag_remove)), + ]); + vec![class("Tags", None, tags, Some(super::function(l, tags_at))), class("Tag", None, tag, None)] +} diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index adcaefd59d..f5c20057f4 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -178,6 +178,7 @@ mod script_folder; mod script_include; mod script_io; mod script_run; +mod script_tags; mod scripts; mod select_effects; mod select_ids_first; diff --git a/crates/engine/src/tests/script_tags.rs b/crates/engine/src/tests/script_tags.rs new file mode 100644 index 0000000000..d84f8d8b40 --- /dev/null +++ b/crates/engine/src/tests/script_tags.rs @@ -0,0 +1,255 @@ +//! Tags on page items: `PageItem.tags`, `Document.tags`, `Tag`, and the `object.tag.*` commands +//! they run. + +use serde_json::{Value, json}; +use vectorcraft_doc::{MAX_TAG_TEXT, MAX_TAGS, ObjectTag}; + +use crate::*; + +fn run(s: &mut Session, source: &str) -> Result { + s.execute("script.run", &json!({"source": source, "name": "t.js"})) +} + +/// What the run logged. +fn log(s: &mut Session, source: &str) -> Vec { + let r = run(s, source).unwrap_or_else(|e| panic!("{source}: {e}")); + r["log"].as_array().cloned().unwrap_or_default() +} + +/// The message of the run's failure. +fn failure(s: &mut Session, source: &str) -> String { + run(s, source).map(|r| panic!("{source} ran: {r}")).unwrap_err().to_string() +} + +fn rect(s: &mut Session, x: f64, y: f64) -> NodeId { + NodeId(s.execute("shape.rectangle", &json!({"x": x, "y": y, "width": 20, "height": 20})).unwrap()["id"].as_u64().unwrap()) +} + +/// A document with two rectangles. +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); + let b = rect(&mut s, 100.0, 100.0); + (s, a, b) +} + +fn undo_steps(s: &Session) -> usize { + s.active().unwrap().history.undo.len() +} + +fn tags(s: &Session, id: NodeId) -> Vec<(String, String)> { + let d = &s.active().unwrap().doc; + crate::cmd::tags::tags_of(d.node(id).unwrap()).iter().map(|t| (t.name.clone(), t.value.clone())).collect() +} + +fn pairs(list: &[(&str, &str)]) -> Vec<(String, String)> { + list.iter().map(|(n, v)| (n.to_string(), v.to_string())).collect() +} + +#[test] +fn tags_are_added_named_read_and_removed_in_one_undo_step() { + let (mut s, a, _) = doc(); + let before = undo_steps(&s); + let out = log( + &mut s, + "var item = app.activeDocument.pageItems[0], tags = item.tags;\ + vc.log(tags.typename); vc.log(tags.length);\ + var t = tags.add(); vc.log(t.typename); vc.log(t.name === '' && t.value === '');\ + t.name = 'size'; t.value = 'XL';\ + var u = tags.add(); u.name = 'size'; u.value = 'S';\ + var w = tags.add(); w.name = '../a\\\\b'; w.value = 'kept';\ + vc.log(tags.length); vc.log(tags.getByName('size').value); vc.log(tags[1].value); vc.log(tags.index(2).name);\ + vc.log(tags.index('../a\\\\b').value); vc.log(tags[3] === undefined); vc.log(t.parent.typename); vc.log(tags.parent.typename);\ + u.remove(); vc.log(tags.length); vc.log(tags[1].name);", + ); + let expected = [json!("Tags"), json!(0), json!("Tag"), json!(true), json!(3), json!("XL"), json!("S"), json!("../a\\b")]; + assert_eq!(out[..8], expected); + assert_eq!(out[8..], [json!("kept"), json!(true), json!("PathItem"), json!("PathItem"), json!(2), json!("../a\\b")]); + assert_eq!(tags(&s, a), pairs(&[("size", "XL"), ("../a\\b", "kept")])); + assert_eq!(undo_steps(&s), before + 1); + s.execute("edit.undo", &json!({})).unwrap(); + assert!(tags(&s, a).is_empty()); + s.execute("edit.redo", &json!({})).unwrap(); + assert_eq!(tags(&s, a).len(), 2); + log(&mut s, "app.activeDocument.pageItems[0].tags.removeAll();"); + assert!(tags(&s, a).is_empty()); +} + +#[test] +fn document_tags_list_every_items_tags_and_add_none() { + let (mut s, a, b) = doc(); + s.execute("object.tag.add", &json!({"id": b.0, "name": "b1", "value": "2"})).unwrap(); + s.execute("object.tag.add", &json!({"id": a.0, "name": "a1", "value": "1"})).unwrap(); + let out = log( + &mut s, + "var d = app.activeDocument; vc.log(d.tags.length); vc.log(d.tags[0].name); vc.log(d.tags[1].name);\ + vc.log(d.tags.parent.typename); vc.log(d.tags.getByName('b1').parent.typename);", + ); + assert_eq!(out, [json!(2), json!("a1"), json!("b1"), json!("Document"), json!("PathItem")]); + // A copy keeps its source's tags. + let copy = s.execute("edit.duplicate", &json!({"ids": [a.0]})).unwrap()["ids"][0].as_u64().map(NodeId).unwrap(); + assert_eq!(tags(&s, copy), pairs(&[("a1", "1")])); + s.execute("edit.undo", &json!({})).unwrap(); + let before = undo_steps(&s); + assert!(failure(&mut s, "app.activeDocument.tags.add();").contains("added to a page item's tags")); + assert_eq!(undo_steps(&s), before); + log(&mut s, "app.activeDocument.tags.removeAll();"); + assert!(tags(&s, a).is_empty() && tags(&s, b).is_empty()); + assert_eq!(undo_steps(&s), before + 1); +} + +#[test] +fn bad_tag_values_throw_and_change_nothing() { + let (mut s, a, _) = doc(); + s.execute("object.tag.add", &json!({"id": a.0, "name": "n", "value": "v"})).unwrap(); + let before = undo_steps(&s); + let tag = "app.activeDocument.pageItems[0].tags[0]"; + assert!(failure(&mut s, &format!("{tag}.name = 5;")).contains("TypeError: name must be a string")); + assert!(failure(&mut s, &format!("{tag}.value = null;")).contains("TypeError: value must be a string")); + let long = format!("{tag}.value = new Array({}).join('x');", MAX_TAG_TEXT + 2); + assert!(failure(&mut s, &long).contains("RangeError: a tag's value is longer than 65,536 bytes")); + assert!(failure(&mut s, "app.activeDocument.pageItems[0].tags.getByName('none');").contains("Not found")); + assert!(failure(&mut s, "app.activeDocument.pageItems[0].tags.index(true);").contains("TypeError")); + // A run that fails after changing a tag puts it back. + assert!(failure(&mut s, &format!("{tag}.value = 'w'; throw new Error('stop');")).contains("stop")); + assert_eq!(tags(&s, a), pairs(&[("n", "v")])); + // Setting what a tag already has runs no command. + log(&mut s, &format!("{tag}.name = 'n'; {tag}.value = 'v';")); + assert_eq!(undo_steps(&s), before); +} + +#[test] +fn tags_work_on_an_item_and_with_tag_ids_above_2_to_the_53() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + let big = (1u64 << 53) + 1; + s.active_mut().unwrap().change_unsaved(|d| std::sync::Arc::make_mut(d).raise_next_id(big)); + let a = rect(&mut s, 10.0, 20.0); + assert_eq!(a.0, big); + let out = log( + &mut s, + "var all = app.activeDocument.pageItems[0].tags, t = all.add(); t.name = 'n'; t.value = 'v';\ + var u = all.add(); u.name = 'm'; vc.log(all.length); vc.log(t.name); vc.log(all[1].name); vc.log(t.parent.typename);\ + t.remove(); vc.log(all.length); vc.log(all[0].name);", + ); + assert_eq!(out, [json!(2), json!("n"), json!("m"), json!("PathItem"), json!(1), json!("m")]); + assert_eq!(tags(&s, a), pairs(&[("m", "")])); +} + +#[test] +fn an_object_takes_at_most_64_tags() { + let (mut s, a, _) = doc(); + let out = log(&mut s, "var t = app.activeDocument.pageItems[0].tags; for (var i = 0; i < 64; i++) t.add(); vc.log(t.length);"); + assert_eq!(out, [json!(MAX_TAGS)]); + let e = failure(&mut s, "app.activeDocument.pageItems[0].tags.add();"); + assert!(e.contains("64 tags"), "{e}"); + assert_eq!(tags(&s, a).len(), MAX_TAGS); +} + +#[test] +fn a_tag_goes_stale_when_it_or_its_item_is_deleted() { + let (mut s, a, b) = doc(); + s.execute("object.tag.add", &json!({"id": a.0, "name": "x"})).unwrap(); + s.execute("object.tag.add", &json!({"id": b.0, "name": "y"})).unwrap(); + let e = failure(&mut s, "var t = app.activeDocument.pageItems[0].tags[0]; t.remove(); t.name;"); + assert!(e.contains("Stale tag"), "{e}"); + // `typename` throws too, on a deleted tag and on the tags of a deleted item (each failed run + // put the document back). + let e = failure(&mut s, "var t = app.activeDocument.pageItems[0].tags[0]; t.remove(); t.typename;"); + assert!(e.contains("Stale tag"), "{e}"); + let e = failure(&mut s, "var i = app.activeDocument.pageItems[1], all = i.tags; i.remove(); all.typename;"); + assert!(e.contains("Stale page item"), "{e}"); + let e = failure(&mut s, "var i = app.activeDocument.pageItems[1], t = i.tags[0], all = i.tags; i.remove(); all.length;"); + assert!(e.contains("Stale page item"), "{e}"); + let e = failure(&mut s, "var i = app.activeDocument.pageItems[1], t = i.tags[0]; i.remove(); t.value;"); + assert!(e.contains("Stale page item"), "{e}"); + // A tag added after another was deleted does not take the deleted one's place. + let e = failure(&mut s, "var all = app.activeDocument.pageItems[0].tags, t = all[0]; t.remove(); all.add(); t.name;"); + assert!(e.contains("Stale tag"), "{e}"); + // Nor when the deleted tag's id was ahead of the document's next id (a tag pasted from + // another document). + let d = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc); + let ahead = d.peek_next_id() + 2; + d.node_mut(a).unwrap().edit_attrs(|at| at.tags = vec![ObjectTag { id: ahead, name: "p".into(), value: String::new() }]); + let e = failure(&mut s, "var all = app.activeDocument.pageItems[0].tags, t = all[0]; t.remove(); all.add(); all.add(); all.add(); t.name;"); + assert!(e.contains("Stale tag"), "{e}"); +} + +#[test] +fn tag_commands_check_their_params_and_skip_unchanged_edits() { + let (mut s, a, _) = doc(); + let tag = s.execute("object.tag.add", &json!({"id": a.0, "name": "k"})).unwrap()["tag"].as_u64().unwrap(); + let before = undo_steps(&s); + assert_eq!(s.execute("object.tag.set", &json!({"id": a.0, "tag": tag, "name": "k"})).unwrap()["changed"], false); + assert_eq!(s.execute("object.tag.removeAll", &json!({"ids": []})).unwrap()["changed"], 0); + assert_eq!(undo_steps(&s), before); + let too_long = "x".repeat(MAX_TAG_TEXT + 1); + for (id, p) in [ + ("object.tag.add", json!({"id": a.0, "name": too_long})), + ("object.tag.add", json!({"id": a.0, "value": 3})), + ("object.tag.add", json!({"id": 999_999})), + ("object.tag.add", json!({"id": "1"})), + ("object.tag.set", json!({"id": a.0, "tag": tag})), + ("object.tag.set", json!({"id": a.0, "tag": tag + 1, "name": "n"})), + ("object.tag.remove", json!({"id": a.0, "tag": -1})), + ("object.tag.removeAll", json!({"ids": [999_999]})), + ("object.tags", json!({})), + ] { + assert!(s.execute(id, &p).is_err(), "{id} {p}"); + } + let layer = s.active().unwrap().doc.layers[0].id; + assert!(s.execute("object.tag.add", &json!({"id": layer.0})).is_err()); + assert_eq!(undo_steps(&s), before); + assert_eq!(s.execute("object.tags", &json!({"id": a.0})).unwrap(), json!({"tags": [{"tag": tag, "name": "k", "value": ""}]})); +} + +#[test] +fn tags_survive_native_save_and_open_and_hostile_ones_are_trimmed() { + let (mut s, a, b) = doc(); + let tag = s.execute("object.tag.add", &json!({"id": a.0, "name": "size", "value": "XL"})).unwrap()["tag"].as_u64().unwrap(); + let mut doc = (*s.active().unwrap().doc).clone(); + let back = vectorcraft_format::load(&vectorcraft_format::save(&doc, false)).unwrap(); + let t = crate::cmd::tags::tags_of(back.node(a).unwrap()); + assert_eq!(t.iter().map(|t| (t.name.as_str(), t.value.as_str())).collect::>(), [("size", "XL")]); + // The tag keeps its id, so `object.tag.set` and `object.tag.remove` still find it. + assert_eq!(t[0].id, tag); + assert!(tag < back.peek_next_id()); + // A file with too many tags, repeated ids and over-long text opens with them within the limits. + doc.node_mut(b).unwrap().edit_attrs(|at| { + at.tags = (0..MAX_TAGS + 10).map(|i| ObjectTag { id: 7, name: format!("t{i}"), value: String::new() }).collect(); + at.tags.insert(0, ObjectTag { id: 1, name: "x".repeat(MAX_TAG_TEXT + 1), value: String::new() }); + }); + // The repeated ids get new ids from the next node id on. + let back = vectorcraft_format::load(&vectorcraft_format::save(&doc, false)).unwrap(); + let t = crate::cmd::tags::tags_of(back.node(b).unwrap()); + assert_eq!(t[0].id, 7); + assert!(t[1..].iter().all(|t| t.id > tag && t.id < back.peek_next_id())); + // An id at the top of the node id range, and one past it: the new ids are the smallest the + // object's other tags do not have. + let top = (1u64 << 62) - 1; + doc.node_mut(a).unwrap().edit_attrs(|at| { + at.tags[0].id = u64::MAX; + at.tags.insert(0, ObjectTag { id: top, name: "top".into(), value: String::new() }); + }); + let back = vectorcraft_format::load(&vectorcraft_format::save(&doc, false)).unwrap(); + // Opening gives both new ids below the next node id, which stays within the node id range. + let fixed: Vec = crate::cmd::tags::tags_of(back.node(a).unwrap()).iter().map(|t| t.id).collect(); + assert_eq!(fixed.len(), 2); + assert!(fixed.iter().all(|id| *id < back.peek_next_id()) && fixed[0] != fixed[1], "{fixed:?}"); + assert_eq!(fixed, [top, 1]); + assert!(back.peek_next_id() <= 1 << 62, "{}", back.peek_next_id()); + // No tag id is left for a new tag: one past the range would not be kept on opening, and one + // below it could be a deleted tag's. + assert_eq!(back.clone().alloc_tag_id(a), None); + let t = crate::cmd::tags::tags_of(back.node(b).unwrap()); + assert_eq!(t.len(), MAX_TAGS); + assert_eq!(t[0].name, "t0"); + // The first tag with the repeated id keeps it; the others get new ones. + assert_eq!(t[0].id, 7); + let mut ids: Vec = t.iter().map(|t| t.id).collect(); + assert!(ids.iter().all(|id| *id < back.peek_next_id())); + ids.sort_unstable(); + ids.dedup(); + assert_eq!(ids.len(), MAX_TAGS); +} diff --git a/crates/engine/tests/it/script_host_vs_scriptcheck.rs b/crates/engine/tests/it/script_host_vs_scriptcheck.rs index ef7c97e951..dc57d033d3 100644 --- a/crates/engine/tests/it/script_host_vs_scriptcheck.rs +++ b/crates/engine/tests/it/script_host_vs_scriptcheck.rs @@ -75,7 +75,7 @@ const INSIDE: &[(&str, &str)] = &[ "", "app Application CoordinateSystem Document DocumentArtboardLayout DocumentColorSpace DocumentPresetType \ DocumentPreviewMode DocumentRasterResolution DocumentTransparencyGrid Documents ElementPlacement Layer PageItem \ - PageItems RulerUnits ZOrderMethod", + PageItems RulerUnits Tag Tags ZOrderMethod", ), ("Application.", "prototype"), ( @@ -90,8 +90,8 @@ const INSIDE: &[(&str, &str)] = &[ "Document.prototype.", "activeLayer activeLayer= artboards artboards= close close= constructor convertCoordinate documentColorSpace \ groupItems groupItems= height layers layers= name pageItems parent pathItems pathItems= rulerOrigin rulerOrigin= \ - rulerUnits saveAs saveAs= selection selection= swatches swatches= symbols symbols= textFrames textFrames= typename \ - views views= width", + rulerUnits saveAs saveAs= selection selection= swatches swatches= symbols symbols= tags textFrames textFrames= \ + typename views views= width", ), ("Layer.", "prototype"), ("Layer.prototype.", "constructor name typename"), @@ -103,10 +103,14 @@ const INSIDE: &[(&str, &str)] = &[ "artworkKnockout artworkKnockout= blendingMode blendingMode= bringInPerspective bringInPerspective= constructor \ controlBounds duplicate editable geometricBounds height height= hidden hidden= isIsolated isIsolated= layer layer= \ left left= locked locked= move name name= note note= opacity opacity= parent pixelAligned pixelAligned= position \ - position= remove resize resize= rotate rotate= selected selected= sliced sliced= tags tags= top top= transform \ + position= remove resize resize= rotate rotate= selected selected= sliced sliced= tags top top= transform \ transform= translate translate= typename uRL uRL= uuid uuid= visibilityVariable visibilityVariable= visibleBounds \ width width= wrapInside wrapInside= wrapOffset wrapOffset= wrapped wrapped= zOrder zOrderPosition", ), + ("Tags.", "prototype"), + ("Tags.prototype.", "add constructor getByName index length parent removeAll typename"), + ("Tag.", "prototype"), + ("Tag.prototype.", "constructor name name= parent remove typename value value="), ("CoordinateSystem.", "ARTBOARDCOORDINATESYSTEM DOCUMENTCOORDINATESYSTEM"), ("DocumentArtboardLayout.", "Column GridByCol GridByRow RLGridByCol RLGridByRow RLRow Row"), ("DocumentColorSpace.", "CMYK RGB"), diff --git a/crates/format/src/lib.rs b/crates/format/src/lib.rs index a8c7358aa7..4065b6c838 100644 --- a/crates/format/src/lib.rs +++ b/crates/format/src/lib.rs @@ -639,6 +639,9 @@ fn load_unpacked(file: unpack::Unpacked<'_>, max_nodes: usize, max_values: usize doc.keep_type_values_in_range(); // Untrusted: ruby ranges over the type's text, clamped to it (after the depth limit too). doc.fix_ruby(); + // Untrusted: at most 64 tags an object, each name and value at most 64 KiB, with distinct ids + // (after the depth limit too). + doc.tidy_tags(); // Untrusted: the raster effects resolution, within 1 to 2400 ppi (72 when it isn't finite). doc.raster_effects_ppi = Some(doc.raster_effects_ppi).filter(|v| v.is_finite()).unwrap_or(72.0).clamp(1.0, 2400.0); // Untrusted: the superscript, subscript and small caps proportions of the type, the graph diff --git a/docs/mcp.md b/docs/mcp.md index 9bc2be8efc..b5dedf2874 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2680,6 +2680,14 @@ app through the global object `vc`, and writes to the Script Console and runs ot `app.beep`, throw an error that says they are not available yet when they are read or assigned. Other members those pages list, such as `app.version` and `Document.save()`, and the members of the pages of the page-item kinds themselves, such as a path's fill, are not defined yet and read as `undefined`. +- `PageItem.tags` and `Document.tags` are `Tags` collections (https://ai-scripting.docsforadobe.dev/jsobjref/Tags/) + with `typename`, `length`, `parent`, `[i]`, `index(key)`, `getByName(name)`, `add()` and `removeAll()`, and each + `Tag` (https://ai-scripting.docsforadobe.dev/jsobjref/Tag/) has `typename`, `name`, `value`, `parent` (its page + item) and `remove()`; they run the `object.tag.*` commands. VectorCraft's own rules: a collection lists the tags in + their order on the object, and `Document.tags` lists every page item's tags in `pageItems` order and throws an error + on `add()`; `add()` gives a tag with an empty name and value; `getByName` gives the first tag with the name; + `name` and `value` take strings of at most 65,536 bytes, and an object has at most 64 tags. A tag that was deleted + throws `Stale tag`, and one whose page item was deleted throws `Stale page item`. - `$.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 @@ -6810,8 +6818,20 @@ range is an error and changes nothing. The help page [Create image maps for web graphics](https://helpx.adobe.com/illustrator/desktop/save-and-export/export-files-to-different-formats/create-image-maps-for-web-graphics.html) describes the same 1 to 30 range; the default of 10 is VectorCraft's own value. +An object's tags are name and value pairs that scripts keep on it (`PageItem.tags`). `object.tags {id}` lists them in +order → `{tags: [{tag, name, value}]}`, where `tag` tells each one apart from the object's other tags. +`object.tag.add {id, name?, value?}` adds one after the others → `{tag}`, `object.tag.set {id, tag, name?, value?}` +changes its name or value → `{changed}`, `object.tag.remove {id, tag}` deletes it, and `object.tag.removeAll {ids?}` +deletes every tag of the objects in `ids` or the selection → `{changed: objects}`; each edit is one undo step, and an +edit that changes nothing adds none. Names may be empty or repeated. An object has at most 64 tags, each name and +value at most 65,536 bytes; a layer or a ruler guide has none, and a bad value is an error that changes nothing, as is +an add in a document whose ids have reached the top of their range (a damaged or hand-made file). The +native file keeps the tags and their `tag` ids, and opening one keeps the first 64 tags of each object whose name and +value are within the limit, giving a new id to a tag whose id is missing, out of range or repeated. Copies keep their source's tags. Other file formats do not write them. + ```json {"name":"run_command","arguments":{"command":"attributes.set","params":{"ids":[12],"url":"https://example.com","imageMap":"rectangle"}}} +{"name":"run_command","arguments":{"command":"object.tag.add","params":{"id":12,"name":"size","value":"XL"}}} {"name":"run_command","arguments":{"command":"path.setFillRule","params":{"rule":"evenOdd"}}} {"name":"invoke_menu","arguments":{"command":"ui.attributesPanelOptions","params":{"count":20}}} ``` diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 3b252b56a6..115f5da6e3 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1025,6 +1025,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - The control server writes each reply through a 64 KiB buffer. On Windows 11 it sends the 17 MB `document.inspect` reply of a document with 50,000 objects on one layer to a client over loopback in 0.09 s instead of 34 s. - Scripts: File › Scripts › Other Script… and `script.run` run a JavaScript file against the open documents as one transaction with one undo step for each changed document. A failed or stopped run puts every document back. `crates/engine/src/tests/script_run.rs`. - Scripts: the global `app` gives the open documents, new documents from a startup preset and a `DocumentPreset`, the active document, each document's selection and its page items with their names, notes, visibility, lock, opacity, position, size, bounds and stacking order, and moves and copies them into or beside other objects, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/Application/, https://ai-scripting.docsforadobe.dev/jsobjref/Documents/, https://ai-scripting.docsforadobe.dev/jsobjref/DocumentPreset/, https://ai-scripting.docsforadobe.dev/jsobjref/Document/, https://ai-scripting.docsforadobe.dev/jsobjref/PageItems/, https://ai-scripting.docsforadobe.dev/jsobjref/PageItem/ and https://ai-scripting.docsforadobe.dev/jsobjref/GroupItem/ describe them; each change runs a command inside the run's transaction (`docs/mcp.md`). Layers, paths, type and the other classes are not there yet. `crates/engine/src/tests/script_dom.rs`. + - Scripts: `PageItem.tags` and `Document.tags` read, add, rename and delete an object's tags, name and value pairs that the native file keeps, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/Tags/ and https://ai-scripting.docsforadobe.dev/jsobjref/Tag/ describe them, through `object.tags` and the `object.tag.*` commands, at most 64 tags an object (`docs/mcp.md`). `crates/engine/src/tests/script_tags.rs`. - Scripts: 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 d8fb245db9a4e4838dc6f34b1c44f859c6d5f3cd Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 14:08:07 -0800 Subject: [PATCH 035/151] Scripts: tag commands reject a null name or value object.tag.add and object.tag.set treated a null name or value as left out, so an add with a null name made a tag and a set with a null name still changed the value. A null is now an error that changes nothing. A test also checks that a Tag whose add the run undid stays stale after the run adds another tag. --- crates/engine/src/cmd/tags.rs | 6 +++++- crates/engine/src/tests/script_tags.rs | 7 +++++++ docs/mcp.md | 2 +- 3 files changed, 13 insertions(+), 2 deletions(-) diff --git a/crates/engine/src/cmd/tags.rs b/crates/engine/src/cmd/tags.rs index 8707e7dc1e..2c5fbbeceb 100644 --- a/crates/engine/src/cmd/tags.rs +++ b/crates/engine/src/cmd/tags.rs @@ -78,8 +78,12 @@ fn tag_index(d: &Document, id: NodeId, p: &Value, c: &str) -> Result { tags_of(n).iter().position(|t| t.id == tag).ok_or_else(|| bad(c, format!("object {} has no tag {tag}", id.0))) } -/// The text `p` gives for `key` (a tag's name or value), at most [`MAX_TAG_TEXT`] bytes. +/// The text `p` gives for `key` (a tag's name or value), at most [`MAX_TAG_TEXT`] bytes. `None` +/// when `p` leaves it out; a null is an error. fn tag_text<'a>(p: &'a Value, key: &str, c: &str) -> Result> { + if p.get(key).is_some_and(Value::is_null) { + return Err(bad(c, format!("`{key}` must be a string"))); + } let t = text_param(p, key, c)?; if t.is_some_and(|t| t.len() > MAX_TAG_TEXT) { return Err(bad(c, format!("a tag's {key} is longer than 65,536 bytes"))); diff --git a/crates/engine/src/tests/script_tags.rs b/crates/engine/src/tests/script_tags.rs index d84f8d8b40..79acc49546 100644 --- a/crates/engine/src/tests/script_tags.rs +++ b/crates/engine/src/tests/script_tags.rs @@ -167,6 +167,10 @@ fn a_tag_goes_stale_when_it_or_its_item_is_deleted() { // A tag added after another was deleted does not take the deleted one's place. let e = failure(&mut s, "var all = app.activeDocument.pageItems[0].tags, t = all[0]; t.remove(); all.add(); t.name;"); assert!(e.contains("Stale tag"), "{e}"); + // Nor after the run undoes the add: the undone document's next id does not give the tag's id + // out again. + let e = failure(&mut s, "var all = app.activeDocument.pageItems[0].tags, t = all.add(); vc.run('edit.undo'); all.add().name = 'u'; t.name;"); + assert!(e.contains("Stale tag"), "{e}"); // Nor when the deleted tag's id was ahead of the document's next id (a tag pasted from // another document). let d = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc); @@ -188,6 +192,9 @@ fn tag_commands_check_their_params_and_skip_unchanged_edits() { for (id, p) in [ ("object.tag.add", json!({"id": a.0, "name": too_long})), ("object.tag.add", json!({"id": a.0, "value": 3})), + ("object.tag.add", json!({"id": a.0, "name": null})), + ("object.tag.set", json!({"id": a.0, "tag": tag, "name": null, "value": "updated"})), + ("object.tag.set", json!({"id": a.0, "tag": tag, "value": null})), ("object.tag.add", json!({"id": 999_999})), ("object.tag.add", json!({"id": "1"})), ("object.tag.set", json!({"id": a.0, "tag": tag})), diff --git a/docs/mcp.md b/docs/mcp.md index b5dedf2874..8b93898c75 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -6824,7 +6824,7 @@ order → `{tags: [{tag, name, value}]}`, where `tag` tells each one apart from changes its name or value → `{changed}`, `object.tag.remove {id, tag}` deletes it, and `object.tag.removeAll {ids?}` deletes every tag of the objects in `ids` or the selection → `{changed: objects}`; each edit is one undo step, and an edit that changes nothing adds none. Names may be empty or repeated. An object has at most 64 tags, each name and -value at most 65,536 bytes; a layer or a ruler guide has none, and a bad value is an error that changes nothing, as is +value at most 65,536 bytes; a layer or a ruler guide has none, and a bad value (a null name or value included) is an error that changes nothing, as is an add in a document whose ids have reached the top of their range (a damaged or hand-made file). The native file keeps the tags and their `tag` ids, and opening one keeps the first 64 tags of each object whose name and value are within the limit, giving a new id to a tag whose id is missing, out of range or repeated. Copies keep their source's tags. Other file formats do not write them. From 78d2a634ddb7d6a459d7e15a9e8bf22d591af38d Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 19:22:33 -0800 Subject: [PATCH 036/151] Quick Pen: a press let go past the drag distance moves the anchor A press on an anchor or a segment of a selected path that is let go past the drag distance now moves what it holds, even when every drag event before the release stayed short. Before, such a release selected the anchor, or on an open end went on drawing from it. A press whose path another command edited while it was down does not move anything. The docs now say that a line stays a line and an arc stays circular beside a moved corner anchor, and that at a moved smooth anchor the handles stay in line and the segments bend to meet. --- ROADMAP.md | 2 +- crates/engine/src/tests/quickpen.rs | 40 +++++++++++++++++++++++++++++ crates/tools/src/quickpen.rs | 18 ++++++++----- crates/tools/src/quickpen/edit.rs | 21 ++++++++++++--- docs/mcp.md | 5 ++-- docs/target-app-parity.md | 2 +- 6 files changed, 73 insertions(+), 15 deletions(-) diff --git a/ROADMAP.md b/ROADMAP.md index 7c7bc4cd7c..b44607adf0 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -149,7 +149,7 @@ Ranked; detail in [docs/roadmap.md](docs/roadmap.md) and [docs/gaps.md](docs/gap - 2026-11-17: Circle Tool Options (double-click the Circle tool): Show Center, Show Radii and Show Diameter switch what the tool shows while a circle is drawn, Color sets the color of the center cross and radius lines, Anchors at Standard Positions off puts the circle's anchors at the points it was drawn through (`shape.circleThroughPoints {anchors: "points"}`), and Third Point by Dragging off draws a three-point circle with three clicks and a two-point circle with a double-click on the second point. A VectorCraft addition: headline numbers unchanged. - 2026-11-19: Quick Pen tool, in the Pen tool's group (Alt+P, Option+P on macOS): clicks or drags add straight lines, continuous arcs or sharp-corner arcs; Alt tapped on its own switches the action, C flips the last arc, `[` and `]` size it, a click on the first point closes the path and a click on an open end continues it (`path.quickPen`, part of #2660). Headline numbers unchanged. - 2026-11-19: Quick Pen toolbar on the canvas while the tool is active: Straight Line, Continuous Arc and Sharp Corner Arc, Flip Arc, and More Options with Hide Toolbar, Pin Toolbar Position and Reset Toolbar Position; it follows the drawing beside the path's last point and its handle drags it (`tool.quickPen.flipArc`, `window.quickPenToolbar`, Window › Quick Pen Toolbar; part of #2660). Headline numbers unchanged. -- 2026-11-19: Quick Pen editing: with no path being drawn, a drag on an anchor or a segment of a selected path moves it, a line staying a line and an arc an arc; a click selects an anchor, Shift-click adds one, and the canvas context menu's Delete removes the selected anchors (`path.moveAnchors`, `edit.clear`; #2660). Headline numbers unchanged. +- 2026-11-19: Quick Pen editing: with no path being drawn, a drag on an anchor or a segment of a selected path moves it, a line staying a line and an arc an arc beside a moved corner anchor (at a smooth anchor the handles stay in line and the segments bend to meet); a click selects an anchor, Shift-click adds one, and the canvas context menu's Delete removes the selected anchors (`path.moveAnchors`, `edit.clear`; #2660). Headline numbers unchanged. - 2026-10-31: Pattern libraries: Window › Swatch Libraries › Patterns and the Swatches panel's library menu open Geometric Patterns, a built-in library of eleven pattern swatches (dots, stripes, checks, a grid and shapes); clicking one adds its pattern and swatch to the document, once, and applies it to the active fill or stroke (`swatch.library.add`). - 2026-11-11: Pattern libraries: Patterns › Grit Textures, a second built-in pattern library, holds eight seamless black textures (Fine Grain, Coarse Grit, Sand, Speckle, Stipple, Scratches, Sparse Flecks and Dense Flecks) on tiles of 18 to 36 pt, each drawn the same way every time; marks that reach past a tile edge continue on the next tile, so the tiles join without a seam (`swatch.library.add`). Scores and estimates unchanged. - 2026-11-11: Pattern libraries: Patterns › Optical Effects, a third built-in pattern library, of VectorCraft's own designs, holds eight black wave, moiré and op-art tiles (Sine Bands, Ripple Lines, Interference Rings, Offset Rings, Warped Checks, Pinched Stripes, Chevron Pulse and Radiating Lenses) of 32 to 48 pt, each drawn the same way every time; each tile is one period of its design, and art that reaches past a tile edge continues on the next tile, so the tiles join without a seam (`swatch.library.add`). Scores and estimates unchanged. diff --git a/crates/engine/src/tests/quickpen.rs b/crates/engine/src/tests/quickpen.rs index 5f41ecedb7..c09fc797d4 100644 --- a/crates/engine/src/tests/quickpen.rs +++ b/crates/engine/src/tests/quickpen.rs @@ -644,6 +644,46 @@ fn a_drag_on_an_open_end_moves_it() { assert_eq!(points(&s), [pt(100.0, 300.0), pt(350.0, 350.0), pt(350.0, 450.0)]); } +/// A press let go past the drag distance moves what it holds even when no drag event went that +/// far: an inner anchor moves, and an open end moves instead of going on drawing. +#[test] +fn a_release_past_the_drag_distance_moves_the_anchor() { + let mut s = session(); + selected_quick_pen_path(&mut s, (100.0, 100.0), json!([{"x": 200, "y": 100}, {"x": 300, "y": 100}])); + let undo = undo_steps(&s); + let v = view(); + s.pointer(&PointerEvent::new(PointerKind::Down, 200.0, 100.0), v).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Drag, 200.0, 102.0), v).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Up, 200.0, 150.0), v).unwrap(); + assert_eq!(points(&s), [pt(100.0, 100.0), pt(200.0, 150.0), pt(300.0, 100.0)]); + assert_eq!(undo_steps(&s), undo + 1); + s.pointer(&PointerEvent::new(PointerKind::Down, 300.0, 100.0), v).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Up, 300.0, 200.0), v).unwrap(); + assert_eq!(points(&s), [pt(100.0, 100.0), pt(200.0, 150.0), pt(300.0, 200.0)]); + assert_eq!(undo_steps(&s), undo + 2); + assert_eq!(paths(&s).len(), 1, "no new path"); +} + +/// When another command edits the path while the press is down, neither a drag nor a release past +/// the drag distance moves the anchor the press found. +#[test] +fn an_edit_during_an_edit_press_stops_the_move() { + let mut s = session(); + let id = selected_quick_pen_path(&mut s, (100.0, 100.0), json!([{"x": 200, "y": 100}, {"x": 300, "y": 100}])); + let v = view(); + for (drag, x) in [(true, 90.0), (false, 80.0)] { + s.pointer(&PointerEvent::new(PointerKind::Down, 200.0, 100.0), v).unwrap(); + s.execute("path.moveAnchor", &json!({"id": id.0, "anchor": 0, "x": x, "y": 90})).unwrap(); + let undo = undo_steps(&s); + if drag { + s.pointer(&PointerEvent::new(PointerKind::Drag, 200.0, 150.0), v).unwrap(); + } + s.pointer(&PointerEvent::new(PointerKind::Up, 200.0, 150.0), v).unwrap(); + assert_eq!(points(&s), [pt(x, 90.0), pt(200.0, 100.0), pt(300.0, 100.0)], "drag: {drag}"); + assert_eq!(undo_steps(&s), undo, "drag: {drag}"); + } +} + /// A click on an anchor selects it alone, Shift-click adds another, and Delete (`edit.clear`, the /// context menu's Delete) then removes both. #[test] diff --git a/crates/tools/src/quickpen.rs b/crates/tools/src/quickpen.rs index 290c0f494a..a8fd4c4fb7 100644 --- a/crates/tools/src/quickpen.rs +++ b/crates/tools/src/quickpen.rs @@ -450,7 +450,7 @@ impl QuickPenTool { return vec![Action::Begin("Quick Pen".into()), Action::Preview(COMMAND.into(), self.params(false)), drawn()]; } if let Some(grab) = edit::grab_at(cx, p, tol) { - self.edit = Some(Edit::new(grab, p, shift)); + self.edit = Some(Edit::new(cx, grab, p, shift)); return vec![]; } if let Some((id, si, at_first)) = open_end_at(cx, p, tol, None) @@ -496,14 +496,18 @@ impl QuickPenTool { } } - /// The release of a press on an anchor or a segment of a selected path: a drag moves what it - /// holds to `p` and ends its undo step. A click on an end of an open path goes on drawing from - /// it, a click on another anchor selects it alone (with Shift, adds it to the selected anchors - /// or takes it out), and a click on a segment starts a new path there. + /// The release of a press on an anchor or a segment of a selected path: a drag, also one let + /// go past the drag distance after shorter drag events, moves what it holds to `p` and ends + /// its undo step. A click on an end of an open path goes on drawing from it, a click on another + /// anchor selects it alone (with Shift, adds it to the selected anchors or takes it out), and a + /// click on a segment starts a new path there. fn release_edit(&mut self, cx: &ToolContext, mut e: Edit, p: Point) -> Vec { - if e.began { + if e.began || p.distance(e.start) >= cx.tol(DRAG_PX) { let mut out = e.drag(cx, p); - out.push(Action::Commit); + // A drag that could not begin (its path changed under the press) has no step to end. + if e.began { + out.push(Action::Commit); + } return out; } match e.grab { diff --git a/crates/tools/src/quickpen/edit.rs b/crates/tools/src/quickpen/edit.rs index ee219a8d63..918db28ad9 100644 --- a/crates/tools/src/quickpen/edit.rs +++ b/crates/tools/src/quickpen/edit.rs @@ -8,11 +8,13 @@ //! of an open path goes on drawing from it, as before. use std::collections::BTreeSet; +use std::sync::Arc; use serde_json::json; -use vectorcraft_doc::{AnchorRef, NodeId, Selection}; +use vectorcraft_doc::{AnchorRef, Node, NodeId, Selection}; use vectorcraft_geom::Point; +use super::{same_node, shared_node}; use crate::draw2::{anchor_in, segment_in, shown_paths}; use crate::guides::{PointSnap, Targets}; use crate::{Action, Cursor, Overlay, ToolContext}; @@ -79,22 +81,33 @@ pub(super) struct Edit { pub(super) shift: bool, /// Whether the press has dragged far enough to move what it holds (an undo step began). pub(super) began: bool, + /// The grabbed path as the document had it when the press went down. + pressed: Option>, snap: Option, pub(super) guides: Vec, } impl Edit { - pub(super) fn new(grab: Grab, start: Point, shift: bool) -> Self { - Self { grab, start, shift, began: false, snap: None, guides: vec![] } + pub(super) fn new(cx: &ToolContext, grab: Grab, start: Point, shift: bool) -> Self { + let pressed = shared_node(cx.doc, grab.id()).cloned(); + Self { grab, start, shift, began: false, pressed, snap: None, guides: vec![] } } /// Moves what the press holds by the drag to `p`. The first move selects the anchor, or the /// segment, unless it is already selected, and begins the undo step; a drag that starts on - /// one of several selected anchors moves them all. + /// one of several selected anchors moves them all. When the grabbed path changed after the + /// press went down, the drag does not begin. pub(super) fn drag(&mut self, cx: &ToolContext, p: Point) -> Vec { let mut out = vec![]; if !self.began { let id = self.grab.id(); + let unchanged = match (cx.doc.node(id), self.pressed.as_ref()) { + (Some(now), Some(then)) => same_node(now, then), + _ => false, + }; + if !unchanged { + return out; + } let Some(picked) = self.grab.anchors(cx) else { return out }; let already = cx.selection.partial(id).is_some_and(|s| picked.iter().all(|a| s.contains(a))); let moving = if already { diff --git a/docs/mcp.md b/docs/mcp.md index add7833de6..d91a32e569 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -7344,8 +7344,9 @@ With no path being drawn (after Escape or Enter, or before the first click), the describes. A drag on one of their anchors moves that anchor, and a drag that starts on one of several selected anchors moves them all; a drag on a segment moves that segment's two ends. The tool selects what it moves (`select.anchors` or `select.segments` with `mode: "set"`) and moves it with `path.moveAnchors {dx, dy, interpolate: -true}`, one undo step per drag: a segment with one moved end is turned and scaled to its new ends, so a line stays a -line and an arc stays an arc through the same angle, and at a smooth point the handles stay in line. A dragged anchor +true}`, one undo step per drag: a segment with one moved end is turned and scaled to its new ends, so beside a corner +anchor a line stays a line and an arc stays an arc through the same angle; at a smooth anchor the handles stay in line +and the segments bend to meet, so an arc there need not stay circular. A dragged anchor snaps to Smart Guides; a dragged segment does not. Escape during the drag takes it back. A click on an anchor selects it alone and Shift-click adds it to the selected anchors or takes it out (`select.anchors` with `"set"` or `"toggle"`). A click on an end of an open path still goes on drawing from it, a drag there moves the end, and a click diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 5058e1f6df..d400f52ec4 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -634,7 +634,7 @@ since 2026-10-01. - **Trim View hides guides and the grid (#8363):** while View › Trim View is on, the canvas and tiled panes draw no ruler guides, no guide paths and no grid, the guides are neither snapped to nor picked, and Show/Hide Guides and Show/Hide Grid are greyed out (menu bar, canvas context menu, Properties) and refuse to run; the stored choices come back when it is turned off, and the rulers stay ([trim view hides guides](https://community.adobe.com/t5/illustrator-discussions/trim-view-hides-guides/td-p/14066140), [guides greyed out](https://community.adobe.com/t5/illustrator-discussions/guides-greyed-out/m-p/11132728)). A drag or double-click on a ruler makes no guide while it is on (no preview, no undo step, a status message). `trim_view_hides_the_guides_and_the_grid`, `trim_view_deselects_selected_guide_paths`, `trim_view_makes_no_guide_from_the_rulers` in `crates/ui-egui/src/canvas/tests.rs`; `trim_view_greys_out_show_guides_and_show_grid` in `crates/ui-egui/src/menus/tests.rs`. - **Recolor picker follow-up (#8031/#4028):** native Lab numeric entry, document/loaded-library swatches in the Color Picker, and Assign-row Pick from Swatches / Limit to Library menus. #4090 provided the double-click picker and #5113 the Assign sliders. Regression tests `native_lab_entry_in_color_picker` and `row_context_menu_pick_from_swatches_and_limit_to_library` exercise the fields and menu callbacks rather than writing their result state. Area score and hours unchanged. -- **Quick Pen editing (#2660):** with no path being drawn, the Quick Pen tool moves an anchor or a segment of a selected path by a drag (`path.moveAnchors` with `interpolate`, one undo step, a line staying a line and an arc an arc), selects an anchor with a click and adds one with Shift-click, and the canvas context menu's Delete removes the selected anchors (`edit.clear`), as [Draw with the Quick Pen tool](https://helpx.adobe.com/illustrator/web/add-and-edit-artwork/draw-and-edit-paths/draw-with-quick-pen-tool.html) describes. Which presses select and which move, and the drag snapping only an anchor, are VectorCraft's own rules. Tests: tools `quickpen::tests::a_selected_paths_anchors_and_segments_show_the_edit_cursors`, engine `tests::quickpen` (`a_drag_on_an_anchor_moves_it_and_the_arc_stays_an_arc`, `a_drag_on_a_segment_moves_its_ends`, `a_drag_on_an_open_end_moves_it`, `clicks_select_anchors_for_delete`, `escape_takes_back_an_anchor_drag`, `a_press_while_drawing_adds_a_piece`), ui-egui `tests::contextmenu::the_quick_pen_menu_deletes_the_selected_anchors`. Score and hours unchanged. +- **Quick Pen editing (#2660):** with no path being drawn, the Quick Pen tool moves an anchor or a segment of a selected path by a drag (`path.moveAnchors` with `interpolate`, one undo step; beside a moved corner anchor a line stays a line and an arc an arc, and at a moved smooth anchor the handles stay in line and the segments bend to meet), selects an anchor with a click and adds one with Shift-click, and the canvas context menu's Delete removes the selected anchors (`edit.clear`), as [Draw with the Quick Pen tool](https://helpx.adobe.com/illustrator/web/add-and-edit-artwork/draw-and-edit-paths/draw-with-quick-pen-tool.html) describes. Which presses select and which move, and the drag snapping only an anchor, are VectorCraft's own rules. Tests: tools `quickpen::tests::a_selected_paths_anchors_and_segments_show_the_edit_cursors`, engine `tests::quickpen` (`a_drag_on_an_anchor_moves_it_and_the_arc_stays_an_arc`, `a_drag_on_a_segment_moves_its_ends`, `a_drag_on_an_open_end_moves_it`, `a_release_past_the_drag_distance_moves_the_anchor`, `clicks_select_anchors_for_delete`, `escape_takes_back_an_anchor_drag`, `a_press_while_drawing_adds_a_piece`), ui-egui `tests::contextmenu::the_quick_pen_menu_deletes_the_selected_anchors`. Score and hours unchanged. - **Quick Pen tool (#2660, in part):** a tool in the Pen tool's group (Alt+P, Option+P on macOS) draws straight lines, continuous arcs and sharp-corner arcs, one undo step per piece; Alt pressed and let go on its own switches the action, C flips the last sharp-corner arc, `[` and `]` change the arc size by 15°, a click on the first point closes the path, a click on an open end continues it, and Escape or Enter ends it (`path.quickPen`), as [Draw with the Quick Pen tool](https://helpx.adobe.com/illustrator/web/add-and-edit-artwork/draw-and-edit-paths/draw-with-quick-pen-tool.html) and [Quick Pen tool keyboard shortcuts](https://helpx.adobe.com/illustrator/web/add-and-edit-artwork/draw-and-edit-paths/quick-pen-tool-keyboard-shortcuts.html) describe. The 180° default arc, its 15° steps, the side an arc bulges to, a dragged piece ending where the press is let go, and C, `[` and `]` changing the arc being dragged are VectorCraft's own rules. Tests: tools `quickpen::tests`, engine `tests::quickpen`, ui-egui `shortcuts::alt_tap::tests`, `alt_p_chooses_the_quick_pen_and_an_alt_tap_switches_its_action` and `brackets_size_the_quick_pen_arc_being_dragged`. Score and hours unchanged. - **Optional compact Tools (#7234):** Window > Toolbars > Compact Tools reduces row and column spacing and the main panel's allocated width in one or two columns, docked or floating. The setting is saved with the UI state and applies to Basic, Advanced and edited main Tools layouts; the selected tool, icon size, footer controls and tool-flyout behavior are retained. Turning it off restores the existing layout, which remains the default. Named custom toolbars and flyout spacing are unchanged. Public regressions in `crates/ui-egui/tests/toolbar_compact.rs` cover the actual toolbar layout against the default control, the command and saved-state roundtrip, tool selection, flyouts, footer controls and short-window reachability. This is an optional layout choice, without a styling-parity or score claim; hours are unchanged. From 17a1a5543f79156528ddb47bcd32edff6eb19b19 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 20:01:41 -0800 Subject: [PATCH 037/151] Quick Pen: a first Shift-click selects one anchor; a segment drag moves its ends A first Shift-click on an anchor of a path selected whole now selects that anchor alone. Before, it selected every other anchor of the path. A drag on a segment now moves only that segment's two ends. Before, when both ends were selected together with other anchors, the drag moved the other anchors too. --- crates/engine/src/tests/quickpen.rs | 27 +++++++++++++++++++++++++++ crates/tools/src/quickpen.rs | 6 +++++- crates/tools/src/quickpen/edit.rs | 11 ++++++++++- 3 files changed, 42 insertions(+), 2 deletions(-) diff --git a/crates/engine/src/tests/quickpen.rs b/crates/engine/src/tests/quickpen.rs index c09fc797d4..d3746d3c8e 100644 --- a/crates/engine/src/tests/quickpen.rs +++ b/crates/engine/src/tests/quickpen.rs @@ -705,6 +705,33 @@ fn clicks_select_anchors_for_delete() { assert!(!left.contains(&pt(200.0, 100.0)) && !left.contains(&pt(300.0, 100.0)), "{left:?}"); } +/// The first Shift-click on an anchor of a path selected whole selects that anchor alone. +#[test] +fn a_first_shift_click_selects_the_anchor_alone() { + let mut s = session(); + let id = selected_quick_pen_path(&mut s, (100.0, 100.0), json!([{"x": 200, "y": 100}, {"x": 300, "y": 100}])); + assert!(s.doc().unwrap().selection.partial(id).is_none(), "the path is selected whole"); + shift_click(&mut s, 200.0, 100.0); + let picked = s.doc().unwrap().selection.partial(id).cloned().unwrap_or_default().into_iter().collect::>(); + assert_eq!(picked, [(0, 1)]); +} + +/// A drag on a segment moves its two ends alone, also when they are selected with another anchor. +#[test] +fn a_segment_drag_moves_only_its_ends() { + let mut s = session(); + let pieces = json!([{"x": 300, "y": 300}, {"x": 300, "y": 400}, {"x": 100, "y": 400}, {"x": 100, "y": 500}]); + let id = selected_quick_pen_path(&mut s, (100.0, 300.0), pieces); + click(&mut s, 300.0, 300.0); + shift_click(&mut s, 300.0, 400.0); + shift_click(&mut s, 100.0, 400.0); + let picked = s.doc().unwrap().selection.partial(id).cloned().unwrap_or_default().into_iter().collect::>(); + assert_eq!(picked, [(0, 1), (0, 2), (0, 3)]); + press(&mut s, &[(300.0, 350.0), (320.0, 350.0), (350.0, 350.0)]); + assert_eq!(points(&s), [pt(100.0, 300.0), pt(350.0, 300.0), pt(350.0, 400.0), pt(100.0, 400.0), pt(100.0, 500.0)]); + assert_eq!(paths(&s).len(), 1); +} + /// Escape during a drag puts the anchor back, and the release then changes nothing. #[test] fn escape_takes_back_an_anchor_drag() { diff --git a/crates/tools/src/quickpen.rs b/crates/tools/src/quickpen.rs index a8fd4c4fb7..f76cf806bf 100644 --- a/crates/tools/src/quickpen.rs +++ b/crates/tools/src/quickpen.rs @@ -512,7 +512,11 @@ impl QuickPenTool { } match e.grab { Grab::Anchor { id, si, ai, .. } if e.shift => { - vec![Action::Exec("select.anchors".into(), json!({"id": id.0, "anchors": [[si, ai]], "mode": "toggle"}))] + // `select.anchors` toggles from every anchor of a path selected whole on its own, + // so the first Shift-click there selects the anchor alone. + let whole = cx.selection.anchors.is_empty() && cx.selection.objects.len() <= 1; + let mode = if whole { "set" } else { "toggle" }; + vec![Action::Exec("select.anchors".into(), json!({"id": id.0, "anchors": [[si, ai]], "mode": mode}))] } Grab::Anchor { id, si, ai, end: true, .. } => self.continue_path(cx, id, si, ai == 0), Grab::Anchor { id, si, ai, .. } => { diff --git a/crates/tools/src/quickpen/edit.rs b/crates/tools/src/quickpen/edit.rs index 918db28ad9..3e1e0509a7 100644 --- a/crates/tools/src/quickpen/edit.rs +++ b/crates/tools/src/quickpen/edit.rs @@ -109,7 +109,16 @@ impl Edit { return out; } let Some(picked) = self.grab.anchors(cx) else { return out }; - let already = cx.selection.partial(id).is_some_and(|s| picked.iter().all(|a| s.contains(a))); + // A drag on one of several selected anchors moves them all; a drag on a segment moves + // its two ends alone. + let already = match self.grab { + Grab::Anchor { .. } => cx.selection.partial(id).is_some_and(|s| picked.iter().all(|a| s.contains(a))), + Grab::Segment { .. } => { + cx.selection.objects == [id] + && cx.selection.anchors.len() == 1 + && cx.selection.partial(id).is_some_and(|s| s.len() == picked.len() && picked.iter().all(|a| s.contains(a))) + } + }; let moving = if already { cx.selection.clone() } else { From 27011606a5bb17761db8c1ae131fcd68023b6803 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 20:20:34 -0800 Subject: [PATCH 038/151] Scripts: run startup scripts at launch and before a chosen script With Preferences > General > Run Startup Scripts on (off by default), the .jsx files of the Startup Scripts folder next to the preferences run when VectorCraft starts and before each script chosen from File > Scripts, installed or Other Script..., one at a time and sorted by name without regard to case. Each runs with the limits of any script and its own undo step; one that cannot be read, is too large or fails is named in the Script Console and the status bar, and the next one runs, then the chosen script. Nothing runs in Safe Mode; after a launch that stopped, they run once Disable and Continue or Start Normally is chosen, and the launch marker names the running startup script so a stop there offers to disable it. script.startup.run runs the folder; script.* is refused inside scripts, so a startup script cannot start another round. --- apps/vectorcraft/src/main.rs | 5 + apps/vectorcraft/src/prefs_dir.rs | 8 + crates/engine/src/cmd/prefscmds.rs | 1 + crates/engine/src/cmd/scripts.rs | 238 ++++++++++++++ crates/engine/src/lib.rs | 12 + crates/engine/src/prefs.rs | 5 + crates/engine/src/script/folder.rs | 6 +- crates/engine/src/script/mod.rs | 26 +- crates/engine/src/script/startup.rs | 126 ++++++++ crates/engine/src/session/documents.rs | 4 + crates/engine/tests/script_startup.rs | 305 ++++++++++++++++++ crates/ui-egui/src/dialogs/safe_mode.rs | 5 +- crates/ui-egui/src/dialogs/script_run.rs | 7 +- crates/ui-egui/src/i18n/bg.tsv | 2 + crates/ui-egui/src/i18n/bs.tsv | 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/gu.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 + .../ui-egui/src/prefs_dialog/descriptions.rs | 4 + crates/ui-egui/src/script_runs.rs | 26 +- crates/ui-egui/src/scripts_menu.rs | 10 +- crates/ui-egui/src/tests/scripts_menu.rs | 64 ++++ crates/ui-egui/tests/safe_mode.rs | 36 +++ docs/mcp.md | 44 +++ docs/target-app-parity.md | 1 + 48 files changed, 978 insertions(+), 11 deletions(-) create mode 100644 crates/engine/src/script/startup.rs create mode 100644 crates/engine/tests/script_startup.rs diff --git a/apps/vectorcraft/src/main.rs b/apps/vectorcraft/src/main.rs index 29cb56bdfa..94799f724a 100644 --- a/apps/vectorcraft/src/main.rs +++ b/apps/vectorcraft/src/main.rs @@ -551,6 +551,8 @@ fn main() -> std::process::ExitCode { prefs_dir::attach_plugin_store(&mut session); // File › Scripts lists the scripts of the Scripts folder next to the preferences. prefs_dir::attach_scripts_dir(&mut session); + // The startup scripts are in the Startup Scripts folder next to the preferences. + prefs_dir::attach_startup_scripts_dir(&mut session); // File Info's metadata templates live in their own folder next to the preferences. prefs_dir::attach_metadata_templates_dir(&mut session); prefs_dir::attach_new_doc_profiles(&mut session); @@ -694,6 +696,9 @@ fn main() -> std::process::ExitCode { } app.services.native_input_hook = native_input_hook(&app); let held_files = file_access::unconfined(|| open_or_hold(&mut app, files)); + // With General › Run Startup Scripts on and Safe Mode off, the startup scripts run + // now, as the person's own; in Safe Mode they wait for the choice that ends it. + file_access::unconfined(|| vectorcraft_ui_egui::script_runs::run_at_launch(&mut app)); // The first frame is due from now (`gpu::watch_first_frame`). #[cfg(feature = "wgpu")] created.ready(); diff --git a/apps/vectorcraft/src/prefs_dir.rs b/apps/vectorcraft/src/prefs_dir.rs index 492e2ea7bf..5738359420 100644 --- a/apps/vectorcraft/src/prefs_dir.rs +++ b/apps/vectorcraft/src/prefs_dir.rs @@ -65,6 +65,14 @@ pub fn attach_scripts_dir(session: &mut vectorcraft_engine::Session) { } } +/// Have `script.startup.run` run the scripts of the `Startup Scripts` folder. The folder is only +/// read: the user makes it. +pub fn attach_startup_scripts_dir(session: &mut vectorcraft_engine::Session) { + if let Some(dir) = store_dir("Startup Scripts") { + session.attach_startup_scripts_dir(dir); + } +} + /// Keep File Info's metadata templates in the `Metadata Templates` folder, which a saved template /// makes. pub fn attach_metadata_templates_dir(session: &mut vectorcraft_engine::Session) { diff --git a/crates/engine/src/cmd/prefscmds.rs b/crates/engine/src/cmd/prefscmds.rs index 46cdee28a5..0d9230a421 100644 --- a/crates/engine/src/cmd/prefscmds.rs +++ b/crates/engine/src/cmd/prefscmds.rs @@ -144,6 +144,7 @@ pub const PREF_SPECS: &[PrefSpec] = &[ p!("showToolTips", "General", "Options", "Show Tool Tips", bool), p!("showToolCards", "General", "Options", "Show Tool Cards", bool), p!("showExternalScriptWarning", "General", "Options", "Show External Script Warning", bool), + p!("runStartupScripts", "General", "Options", "Run Startup Scripts", bool), p!("antiAliasedArtwork", "General", "Options", "Anti-aliased Artwork", bool), p!("selectSameTintPercent", "General", "Options", "Select Same Tint %", bool), p!("showHomeScreen", "General", "Options", "Show The Home Screen When No Documents Are Open", bool), diff --git a/crates/engine/src/cmd/scripts.rs b/crates/engine/src/cmd/scripts.rs index cf46d853d8..65670444d9 100644 --- a/crates/engine/src/cmd/scripts.rs +++ b/crates/engine/src/cmd/scripts.rs @@ -90,6 +90,15 @@ pub fn specs() -> Vec { always, list_installed ), + cmd!( + query "script.startup.run", + "Run Startup Scripts", + [], + None, + "{reason: launch|menu (launch: the app starting; menu: before a script chosen from File › Scripts), then?: script.run's parameters (the script to run once the startup scripts have run), maxFuel?: whole number from 1 to 100000000000 (each startup script's instructions; default 1000000000)} run the .jsx files of the Startup Scripts folder next to the settings, one at a time, as script.run runs a file, each with the same limits as any script and its own undo step; nothing runs, and the reply says why, when the runStartupScripts preference is off (the default), in Safe Mode, or in a session without the folder (the web, and a run with VECTORCRAFT_NO_PREFS); only the folder's own .jsx files run, sorted by name without regard to case, then by name; links, hidden files, names starting with a dot, subfolders and other files are left out, and so is a script the Safe Mode choice disabled; a missing folder runs nothing; a script that cannot be read, is larger than 8 MiB, fails or is stopped is named in failed and in the Script Console, and the next one runs, then the script of then; while a startup script runs, the launch marker names it, so a launch that stops there offers to disable it; script.* commands are refused inside a script, so a startup script does not start another startup run. VectorCraft's own rules: the folder, the order, the limits of a listing (2048 folder entries, 512 scripts, 250 ms) and what a failure does → {reason, skipped: true, why: off|safeMode|noFolder, then?: script.run's reply} | {reason, skipped: false, ran: [names], failed: [{name, error}], disabled: [names], truncated, unreadable, then?: script.run's reply}, or, in the app, {reason, skipped: false, running, queued: the runs queued, then's included, failed: [{name, error}] (the runs that could not start before the first one did), disabled, truncated, unreadable, then?: script.run's reply when it ran to its end at once}, each run then reporting as script.run's do, and a later run that cannot start is named in the status bar", + always, + startup_run + ), cmd!( query "script.grants", "List Script File Permissions", @@ -342,6 +351,235 @@ impl Session { } } +/// The error of a startup script that is no longer a `.jsx` file of the Startup Scripts folder, or +/// cannot be read, when its turn comes. +pub const STARTUP_UNREADABLE: &str = "the startup script could not be read"; + +impl Session { + /// Have `script.startup.run` run the scripts of the folder `dir`. The folder is only read, and + /// never made. + pub fn attach_startup_scripts_dir(&mut self, dir: std::path::PathBuf) { + self.startup_scripts_dir = Some(dir); + } + + /// The Startup Scripts folder ([`Session::attach_startup_scripts_dir`]); none on the web. + pub fn startup_scripts_dir(&self) -> Option<&std::path::Path> { + self.startup_scripts_dir.as_deref().filter(|_| !cfg!(target_arch = "wasm32")) + } + + /// Why `script.startup.run` runs nothing now: `off` (the `runStartupScripts` preference), + /// `safeMode`, or `noFolder` (no Startup Scripts folder); `None` when it runs the folder. + pub fn startup_skip(&self) -> Option<&'static str> { + if !self.prefs.run_startup_scripts { + Some("off") + } else if vectorcraft_plugins::safe_mode::active() { + Some("safeMode") + } else if self.startup_scripts_dir().is_none() { + Some("noFolder") + } else { + None + } + } + + /// The startup script that ran has ended: the launch marker no longer names it. + pub(crate) fn startup_ended(&mut self) { + if let Some(token) = self.startup_loading.take() { + vectorcraft_plugins::safe_mode::loaded(token); + } + } + + /// Begins a run of the startup script at `path`, read now and checked as `script.run` checks a + /// file, with the launch marker naming it while it runs. → the run's name, or the error that kept + /// it from starting, which the Script Console also shows. + fn start_startup(&mut self, path: &std::path::Path, fuel: u64) -> std::result::Result { + let name = file_name_of(path); + let text = self.startup_text(path); + let (text, real) = match text { + Ok(read) => read, + Err(message) => { + self.note_unread(&name, &message); + return Err(message); + } + }; + let item = startup_item(path); + self.startup_loading = Some(vectorcraft_plugins::safe_mode::loading(&item)); + let locale = script::dollar::ui_locale(self.ui_language.as_deref().unwrap_or(&self.prefs.interface_language)); + let request = script::Request { + name, + name_given: false, + file: Some(path.to_string_lossy().into_owned()), + checked_real: Some(real), + source: text, + args: serde_json::Map::new(), + fuel, + locale, + answers: vec![], + }; + self.script_start(request).map_err(|e| { + self.startup_ended(); + e.to_string() + }) + } + + /// The text of the startup script at `path` and its real path, or the error that keeps it from + /// running. + fn startup_text(&self, path: &std::path::Path) -> std::result::Result<(String, std::path::PathBuf), String> { + let unreadable = || STARTUP_UNREADABLE.to_string(); + let root = self.startup_scripts_dir().ok_or_else(unreadable)?; + let mut real = std::fs::canonicalize(root).map_err(|_| unreadable())?; + real.push(path.file_name().ok_or_else(unreadable)?); + // One byte more than a script may have shows that the file is too large. + let bytes = script::startup::read(root, path, script::MAX_SOURCE_BYTES + 1).ok_or_else(unreadable)?; + if bytes.len() > script::MAX_SOURCE_BYTES { + return Err(TOO_LARGE.to_string()); + } + Ok((script_text(&bytes).map_err(|e| e.to_string())?, real)) + } + + /// With no script running, starts the next run `script.startup.run` queued: the next startup + /// script that starts, or the script queued after them. A run that cannot start is kept for + /// [`Self::take_startup_failures`], and the next one starts. → the reply of the script queued + /// after them when it ran to its end at once. + pub(crate) fn start_queued(&mut self) -> Option { + while !self.script_running() { + match self.script_queue.pop_front()? { + script::startup::Queued::Startup { path, fuel } => { + if let Err(e) = self.start_startup(&path, fuel) { + self.startup_failures.push((file_name_of(&path), e)); + } + } + script::startup::Queued::Then(params) => { + match run(self, ¶ms) { + Ok(_) if self.script_running() => {} + Ok(v) => return Some(v), + Err(e) => self.startup_failures.push((then_name(¶ms), e.to_string())), + } + return None; + } + } + } + None + } + + /// The runs `script.startup.run` queued that could not start since the last call, as (name, + /// error), in order. + pub fn take_startup_failures(&mut self) -> Vec<(String, String)> { + std::mem::take(&mut self.startup_failures) + } +} + +/// The file name of `path`, or the whole path when it has none. +fn file_name_of(path: &std::path::Path) -> String { + path.file_name().map_or_else(|| path.to_string_lossy().into_owned(), |n| n.to_string_lossy().into_owned()) +} + +/// The name a failure of the script `params` (`script.run`'s) names it by: `name`, else the file +/// name of `path`, else "script". +fn then_name(params: &Value) -> String { + let given = |key: &str| params.get(key).and_then(Value::as_str).filter(|v| !v.trim().is_empty()); + match (given("name"), given("path")) { + (Some(name), _) => name.to_string(), + (None, Some(path)) => file_name_of(std::path::Path::new(path)), + (None, None) => "script".to_string(), + } +} + +/// The launch marker's entry for the startup script at `path`: its file and its file name. +fn startup_item(path: &std::path::Path) -> vectorcraft_plugins::safe_mode::Item { + let name = path.file_name().map(|n| n.to_string_lossy().into_owned()); + vectorcraft_plugins::safe_mode::Item { id: None, file: Some(path.to_string_lossy().into_owned()), name } +} + +fn startup_run(s: &mut Session, p: &Value) -> Result { + const C: &str = "script.startup.run"; + let reason = match p.get("reason").and_then(Value::as_str) { + Some(r @ ("launch" | "menu")) => r, + _ => { + let key = "reason"; + return Err(bad(C, format!("`{key}` must be one of {}", "launch, menu"))); + } + }; + let then = match p.get("then") { + None => None, + Some(v @ Value::Object(_)) => Some(v.clone()), + Some(_) => { + let key = "then"; + return Err(bad(C, format!("`{key}` must be an object"))); + } + }; + let fuel = match p.get("maxFuel") { + None => script::DEFAULT_FUEL, + Some(v) => v.as_u64().filter(|n| (1..=script::MAX_FUEL).contains(n)).ok_or_else(|| EngineError::BadParams { + cmd: C.into(), + msg: format!("`maxFuel` must be a whole number from 1 to {}", script::MAX_FUEL), + })?, + }; + if s.script_running() { + return Err(EngineError::Busy); + } + let root = match (s.startup_skip(), s.startup_scripts_dir()) { + (None, Some(root)) => root.to_path_buf(), + (why, _) => { + let mut out = json!({"reason": reason, "skipped": true, "why": why.unwrap_or("noFolder")}); + if let Some(then) = then { + out["then"] = run(s, &then)?; + } + return Ok(out); + } + }; + let folder = root.to_string_lossy().into_owned(); + // The folder is the app's: a refusal names it as the request may see it. + crate::file_access::check_read(&folder).map_err(|e| super::fileio::naming_in_error(EngineError::Other(e), &folder))?; + let listing = script::startup::list(&root); + let name_of = |path: &std::path::Path| path.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default(); + let (disabled, scripts): (Vec<_>, Vec<_>) = + listing.scripts.into_iter().partition(|path| vectorcraft_plugins::safe_mode::skipped(&startup_item(path))); + let disabled: Vec = disabled.iter().map(|p| name_of(p)).collect(); + if s.script_frames { + s.script_queue = + scripts.into_iter().map(|path| script::startup::Queued::Startup { path, fuel }).chain(then.map(script::startup::Queued::Then)).collect(); + let queued = s.script_queue.len(); + s.startup_failures.clear(); + let then = s.start_queued(); + let failed: Vec = s.startup_failures.iter().map(|(name, error)| json!({"name": name, "error": error})).collect(); + let mut out = json!({ + "reason": reason, + "skipped": false, + "running": s.script_running(), + "queued": queued, + "failed": failed, + "disabled": disabled, + "truncated": listing.truncated, + "unreadable": listing.unreadable, + }); + if let Some(then) = then { + out["then"] = then; + } + return Ok(out); + } + let (mut ran, mut failed) = (vec![], vec![]); + for path in scripts { + let name = name_of(&path); + match s.start_startup(&path, fuel).map_err(EngineError::Other).and_then(|_| s.script_run_to_end()) { + Ok(_) => ran.push(name), + Err(e) => failed.push(json!({"name": name, "error": e.to_string()})), + } + } + let mut out = json!({ + "reason": reason, + "skipped": false, + "ran": ran, + "failed": failed, + "disabled": disabled, + "truncated": listing.truncated, + "unreadable": listing.unreadable, + }); + if let Some(then) = then { + out["then"] = run(s, &then)?; + } + Ok(out) +} + /// The file name a reply names `path` by when the file is outside the automation read roots; `None` /// when a reply may name it whole. fn hidden_name(path: &str) -> Option { diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index e2e6430f1e..1e08f69e24 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -192,6 +192,9 @@ pub struct Session { /// The Scripts folder, whose scripts File › Scripts lists; `None`: no folder /// ([`Session::attach_scripts_dir`]). scripts_dir: Option, + /// The Startup Scripts folder, whose scripts `script.startup.run` runs; `None`: no folder + /// ([`Session::attach_startup_scripts_dir`]). + startup_scripts_dir: Option, /// The folder of File Info's metadata templates; `None`: no folder /// ([`Session::attach_metadata_templates_dir`]). metadata_templates_dir: Option, @@ -307,6 +310,15 @@ pub struct Session { /// `script.run` starts the job and returns, and the frontend advances it once per frame /// ([`Session::script_pump`]). Off, `script.run` advances it to its end. pub script_frames: bool, + /// The runs `script.startup.run` queued in the app, each started when the run before it ends + /// ([`Session::script_pump`]). + pub(crate) script_queue: std::collections::VecDeque, + /// While a startup script runs: the launch marker's entry naming it + /// ([`vectorcraft_plugins::safe_mode::loading`]). + pub(crate) startup_loading: Option, + /// The queued runs that could not start, as (name, error), until the frontend takes them + /// ([`Session::take_startup_failures`]). + pub(crate) startup_failures: Vec<(String, String)>, /// Each open document's highest next id a run has seen, by [`DocState::uid`]. pub(crate) script_high_water: std::collections::HashMap, /// While a slice of a script runs in this session. diff --git a/crates/engine/src/prefs.rs b/crates/engine/src/prefs.rs index 2e0d0f9fe4..2443dfdd06 100644 --- a/crates/engine/src/prefs.rs +++ b/crates/engine/src/prefs.rs @@ -62,6 +62,10 @@ pub struct Prefs { pub show_tool_cards: bool, /// Other Script… warns before it runs a chosen script. pub show_external_script_warning: bool, + /// General › Run Startup Scripts: the `.jsx` files of the Startup Scripts folder run when the + /// app starts and before each script chosen from File › Scripts (`script.startup.run`). Off by + /// default. + pub run_startup_scripts: bool, pub anti_aliased_artwork: bool, pub select_same_tint_percent: bool, pub show_home_screen: bool, @@ -468,6 +472,7 @@ impl Default for Prefs { show_tool_tips: true, show_tool_cards: false, show_external_script_warning: true, + run_startup_scripts: false, anti_aliased_artwork: true, select_same_tint_percent: false, show_home_screen: true, diff --git a/crates/engine/src/script/folder.rs b/crates/engine/src/script/folder.rs index d071195df6..9ec36c2447 100644 --- a/crates/engine/src/script/folder.rs +++ b/crates/engine/src/script/folder.rs @@ -237,7 +237,7 @@ fn hidden(entry: &std::fs::DirEntry) -> bool { /// Does Windows mark the file or folder of `m` hidden or system? #[cfg(windows)] -fn hidden_meta(m: &std::fs::Metadata) -> bool { +pub(super) fn hidden_meta(m: &std::fs::Metadata) -> bool { use std::os::windows::fs::MetadataExt as _; const HIDDEN_OR_SYSTEM: u32 = 0x2 | 0x4; m.file_attributes() & HIDDEN_OR_SYSTEM != 0 @@ -245,13 +245,13 @@ fn hidden_meta(m: &std::fs::Metadata) -> bool { /// Elsewhere a hidden file is one whose name starts with a dot, which the listing leaves out by name. #[cfg(not(windows))] -fn hidden_meta(_: &std::fs::Metadata) -> bool { +pub(super) fn hidden_meta(_: &std::fs::Metadata) -> bool { false } /// Is `path` a folder (`folder`) or a file, and not a link? With `shown`, also not one Windows /// marks hidden or system, which a listing leaves out. -fn plain(path: &Path, folder: bool, shown: bool) -> bool { +pub(super) fn plain(path: &Path, folder: bool, shown: bool) -> bool { std::fs::symlink_metadata(path) .is_ok_and(|m| !m.file_type().is_symlink() && (if folder { m.is_dir() } else { m.is_file() }) && !(shown && hidden_meta(&m))) } diff --git a/crates/engine/src/script/mod.rs b/crates/engine/src/script/mod.rs index 0e702c0076..f5c1326c8d 100644 --- a/crates/engine/src/script/mod.rs +++ b/crates/engine/src/script/mod.rs @@ -71,6 +71,7 @@ use crate::{ pub mod files; pub mod folder; +pub mod startup; /// The most bytes of source a run takes, as a file or as `source`. pub const MAX_SOURCE_BYTES: usize = 8 << 20; @@ -1879,6 +1880,9 @@ impl Session { /// Stops the running script at once and puts everything back, with the report of a stopped run /// ([`Self::script_report`]). False with none running. pub fn script_abandon(&mut self) -> bool { + // The runs queued after it are not started. + self.script_queue.clear(); + self.startup_ended(); let Some(key) = self.script_key.take() else { return false }; let Some(job) = JOBS.with(|jobs| jobs.borrow_mut().remove(&key.id)) else { self.script_gone(key, console::Ending::Stopped); @@ -1911,6 +1915,16 @@ impl Session { cmd::compositefonts::sync(self); } + /// A script named `name` that did not start because its file could not be read as a script: + /// the Script Console gets a run with a start line, `message` as its error and an end line. + pub(crate) fn note_unread(&mut self, name: &str, message: &str) { + self.script_runs += 1; + let name = console::line_name(name); + for entry in [console::Entry::Start, console::Entry::Error(format!("{name}: {message}")), console::Entry::End(console::Ending::Error)] { + self.script_console.push(console::ConsoleLine { run: self.script_runs, name: name.clone(), entry }, false); + } + } + /// A script can't start while a document holds a drag in progress or an undo group, which its /// one undo step could not take in. fn settle_for_script(&mut self) -> Result<()> { @@ -2109,8 +2123,18 @@ impl Session { } /// Advances the running script by one slice. `None` while it is still running; otherwise the - /// run has ended: its report, or the error that ended it, with the documents put back. + /// run has ended: its report, or the error that ended it, with the documents put back. When + /// `script.startup.run` queued more runs, the next one starts then, and a queued run that cannot + /// start is kept for [`Self::take_startup_failures`]. pub fn script_pump(&mut self) -> Option> { + let result = self.pump_one()?; + self.startup_ended(); + self.start_queued(); + Some(result) + } + + /// [`Self::script_pump`] for the running script alone. + fn pump_one(&mut self) -> Option> { let key = self.script_key.take()?; let Some(mut job) = JOBS.with(|jobs| jobs.borrow_mut().remove(&key.id)) else { self.script_gone(key, console::Ending::Internal); diff --git a/crates/engine/src/script/startup.rs b/crates/engine/src/script/startup.rs new file mode 100644 index 0000000000..17578da3ba --- /dev/null +++ b/crates/engine/src/script/startup.rs @@ -0,0 +1,126 @@ +//! The Startup Scripts folder: the `.jsx` files `script.startup.run` runs, one after another, when +//! the app starts and before a script chosen from File › Scripts runs ([`list`]), and the read of +//! one of them when its turn comes ([`read`]). +//! +//! Only the folder's own files are taken, never its subfolders. A listing follows no link: a +//! symbolic link or a Windows junction is left out, and so is a folder that is itself a link. Names +//! that start with a dot, files Windows marks hidden or system, names that are not Unicode, names +//! longer than [`folder::MAX_NAME_BYTES`] and files whose extension is not `.jsx` are left out too. +//! The files are sorted by name without regard to case, then by name. +//! +//! The limits are the Scripts folder's ([`folder::MAX_ENTRIES`], [`folder::MAX_SCRIPTS`] and +//! [`folder::MAX_SCAN`]), VectorCraft's own values. A listing that reaches one keeps what it found +//! and says so ([`Listing::truncated`]). + +use std::io::Read; +use std::path::{Path, PathBuf}; +use std::time::Duration; + +use super::folder; + +/// What a Startup Scripts folder holds. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct Listing { + /// The scripts, in the order they run. + pub scripts: Vec, + /// Some scripts may be missing: a limit was reached or an entry could not be read. + pub truncated: bool, + /// The folder is there and could not be read, or is a link. + pub unreadable: bool, +} + +/// Does the file name `name` name a startup script: a `.jsx` file (in any case) whose name does not +/// start with a dot and has at most [`folder::MAX_NAME_BYTES`] bytes? +pub fn takes(name: &str) -> bool { + !name.starts_with('.') + && name.len() <= folder::MAX_NAME_BYTES + && Path::new(name).extension().and_then(|e| e.to_str()).is_some_and(|e| e.eq_ignore_ascii_case("jsx")) +} + +/// The startup scripts in `root`, within the Scripts folder's limits. A folder that does not exist +/// gives an empty listing. +pub fn list(root: &Path) -> Listing { + let start = std::time::Instant::now(); + list_with(root, &folder::Limits::default(), &mut || start.elapsed()) +} + +/// The startup scripts in `root`, within `limits` (the entries, scripts and time ones); +/// `elapsed` says how long the listing has taken. +pub fn list_with(root: &Path, limits: &folder::Limits, elapsed: &mut dyn FnMut() -> Duration) -> Listing { + let unreadable = Listing { unreadable: true, ..Listing::default() }; + match std::fs::symlink_metadata(root) { + Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Listing::default(), + Err(_) => return unreadable, + Ok(m) if m.file_type().is_symlink() || !m.is_dir() => return unreadable, + Ok(_) => {} + } + if root.to_str().is_none() { + return unreadable; + } + let Ok(entries) = std::fs::read_dir(root) else { return unreadable }; + let mut listing = Listing::default(); + let mut names: Vec = vec![]; + for (visited, entry) in entries.enumerate() { + if visited >= limits.entries || elapsed() > limits.time { + listing.truncated = true; + break; + } + let Ok(entry) = entry else { + listing.truncated = true; + continue; + }; + let Ok(name) = entry.file_name().into_string() else { continue }; + if !takes(&name) { + continue; + } + let Ok(kind) = entry.file_type() else { + listing.truncated = true; + continue; + }; + if !kind.is_file() || kind.is_symlink() || entry.metadata().is_ok_and(|m| folder::hidden_meta(&m)) { + continue; + } + if names.len() >= limits.scripts { + listing.truncated = true; + continue; + } + names.push(name); + } + names.sort_by(|a, b| (a.to_lowercase(), a).cmp(&(b.to_lowercase(), b))); + listing.scripts = names.into_iter().map(|n| root.join(n)).collect(); + listing +} + +/// Is `path` a startup script a listing of `root` can hold now: a file [`takes`] names, directly in +/// `root`, where neither `root` nor the file is a link and the file is not marked hidden or system? +pub fn holds(root: &Path, path: &Path) -> bool { + if path.parent() != Some(root) { + return false; + } + let Some(name) = path.file_name().and_then(|n| n.to_str()) else { return false }; + takes(name) && folder::plain(root, true, false) && folder::plain(path, false, true) +} + +/// The first `max` bytes of the startup script at `path`, or `None` when [`holds`] does not hold for +/// it before the read and again after it, or it cannot be read. +pub fn read(root: &Path, path: &Path, max: usize) -> Option> { + if !holds(root, path) { + return None; + } + let file = std::fs::File::open(path).ok()?; + if !file.metadata().is_ok_and(|m| m.is_file()) { + return None; + } + let mut bytes = vec![]; + file.take(max as u64).read_to_end(&mut bytes).ok()?; + holds(root, path).then_some(bytes) +} + +/// A run `script.startup.run` queued for the app, which starts it when the run before it ends. +#[derive(Clone, Debug, PartialEq)] +pub enum Queued { + /// A startup script, read when its turn comes, with its `maxFuel`. + Startup { path: PathBuf, fuel: u64 }, + /// The script that runs after the startup scripts, as `script.run`'s parameters. + Then(serde_json::Value), +} diff --git a/crates/engine/src/session/documents.rs b/crates/engine/src/session/documents.rs index 61dbdb4491..e312a30b21 100644 --- a/crates/engine/src/session/documents.rs +++ b/crates/engine/src/session/documents.rs @@ -100,6 +100,7 @@ impl Session { color_settings_file: None, plugin_dir: None, scripts_dir: None, + startup_scripts_dir: None, metadata_templates_dir: None, new_doc_profile_dir: None, proof_setup_dir: None, @@ -164,6 +165,9 @@ impl Session { script_console: Default::default(), script_runs: 0, script_frames: false, + script_queue: Default::default(), + startup_loading: None, + startup_failures: vec![], script_high_water: Default::default(), script_in_run: false, script_copy_first: cfg!(target_arch = "wasm32"), diff --git a/crates/engine/tests/script_startup.rs b/crates/engine/tests/script_startup.rs new file mode 100644 index 0000000000..74afe9efa5 --- /dev/null +++ b/crates/engine/tests/script_startup.rs @@ -0,0 +1,305 @@ +//! Startup scripts (`script.startup.run`): off by default, the folder's `.jsx` files in order at +//! launch and before a chosen script, Safe Mode and disabled scripts, failures and limits, and the +//! launch marker naming the startup script that runs. +//! +//! A test binary of its own: Safe Mode, the disabled list and the launch marker are process-wide, +//! so these tests run one at a time and no other test sees them. +// Integration tests: unwrapping and panicking on failure is fine here, unlike in shipped code (AGENTS.md › Robustness). +#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] + +use std::path::{Path, PathBuf}; +use std::sync::Mutex; + +use serde_json::{Value, json}; +use vectorcraft_engine::Session; +use vectorcraft_plugins::safe_mode; + +static LOCK: Mutex<()> = Mutex::new(()); + +/// Safe Mode off, nothing disabled, no launch marker. +fn reset() { + safe_mode::end_launch(); + safe_mode::set_active(None); + safe_mode::forget_previous(); + safe_mode::set_disabled(vec![]); +} + +/// Holds the lock for one test and resets the process-wide state when the test starts and when it +/// ends, so a test that fails leaves the next one as it would find a new process. +struct Fresh { + _guard: std::sync::MutexGuard<'static, ()>, +} + +fn fresh() -> Fresh { + let guard = LOCK.lock().unwrap_or_else(|e| e.into_inner()); + reset(); + Fresh { _guard: guard } +} + +impl Drop for Fresh { + fn drop(&mut self) { + reset(); + } +} + +/// A new, empty folder for test `tag`. +fn tmp_dir(tag: &str) -> PathBuf { + let d = std::env::temp_dir().join(format!("vc-script-startup-{tag}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&d); + std::fs::create_dir_all(&d).unwrap(); + d +} + +/// Writes `text` to `name` under `dir`, folders included. +fn write(dir: &Path, name: &str, text: &str) -> PathBuf { + let path = dir.join(name); + std::fs::create_dir_all(path.parent().unwrap()).unwrap(); + std::fs::write(&path, text).unwrap(); + path +} + +/// A session with the Startup Scripts folder `dir` and Run Startup Scripts on. +fn session(dir: &Path) -> Session { + let mut s = Session::new(); + s.attach_startup_scripts_dir(dir.to_path_buf()); + s.execute("prefs.set", &json!({"key": "runStartupScripts", "value": true})).unwrap(); + s +} + +/// The names of the runs the Script Console started, in order. +fn started(s: &Session) -> Vec { + let lines = s.script_console().to_json(); + lines["lines"].as_array().unwrap().iter().filter(|l| l["kind"] == "start").map(|l| l["name"].as_str().unwrap().to_string()).collect() +} + +/// The texts of the Script Console's lines of `kind`. +fn console(s: &Session, kind: &str) -> Vec { + let lines = s.script_console().to_json(); + lines["lines"].as_array().unwrap().iter().filter(|l| l["kind"] == kind).map(|l| l["text"].as_str().unwrap().to_string()).collect() +} + +fn names(v: &Value) -> Vec<&str> { + v.as_array().unwrap().iter().map(|n| n.as_str().unwrap()).collect() +} + +#[test] +fn startup_scripts_are_off_by_default_and_run_nothing() { + let _f = fresh(); + let dir = tmp_dir("off"); + write(&dir, "a.jsx", "vc.log('ran');"); + let mut s = Session::new(); + assert!(!s.prefs.run_startup_scripts, "off by default"); + s.attach_startup_scripts_dir(dir.clone()); + assert_eq!(s.startup_skip(), Some("off")); + let r = s.execute("script.startup.run", &json!({"reason": "launch"})).unwrap(); + assert_eq!(r, json!({"reason": "launch", "skipped": true, "why": "off"})); + let r = s.execute("script.startup.run", &json!({"reason": "menu", "then": {"source": "vc.log(1);", "name": "chosen"}})).unwrap(); + assert_eq!(r["skipped"], true); + assert_eq!(r["then"]["ok"], true, "the chosen script still runs"); + assert_eq!(started(&s), ["chosen"], "no startup script ran"); +} + +#[test] +fn the_folders_jsx_files_run_in_name_order_at_launch_and_before_a_chosen_script() { + let _f = fresh(); + let dir = tmp_dir("order"); + for name in ["b.jsx", "C.JSX", "a.jsx", ".hidden.jsx", "x.js", "lib.jsxinc", "sub/d.jsx", "notes.txt"] { + write(&dir, name, "vc.log(1);"); + } + let mut s = session(&dir); + let r = s.execute("script.startup.run", &json!({"reason": "launch"})).unwrap(); + assert_eq!(r["skipped"], false); + assert_eq!(names(&r["ran"]), ["a.jsx", "b.jsx", "C.JSX"], "by name without regard to case"); + assert!(r["failed"].as_array().unwrap().is_empty()); + assert_eq!(started(&s), ["a.jsx", "b.jsx", "C.JSX"]); + let r = s.execute("script.startup.run", &json!({"reason": "menu", "then": {"source": "vc.log(2);", "name": "chosen"}})).unwrap(); + assert_eq!(r["then"]["ok"], true); + assert_eq!(started(&s), ["a.jsx", "b.jsx", "C.JSX", "a.jsx", "b.jsx", "C.JSX", "chosen"], "the startup scripts run first"); +} + +#[test] +fn a_missing_folder_runs_nothing_and_a_session_without_one_skips() { + let _f = fresh(); + let dir = tmp_dir("missing"); + let mut s = session(&dir.join("Startup Scripts")); + let r = s.execute("script.startup.run", &json!({"reason": "launch"})).unwrap(); + assert_eq!(r["skipped"], false); + assert!(r["ran"].as_array().unwrap().is_empty() && r["failed"].as_array().unwrap().is_empty()); + assert_eq!(r["unreadable"], false); + let mut s = Session::new(); + s.execute("prefs.set", &json!({"key": "runStartupScripts", "value": true})).unwrap(); + let r = s.execute("script.startup.run", &json!({"reason": "launch"})).unwrap(); + assert_eq!(r["why"], "noFolder"); +} + +#[test] +fn safe_mode_skips_the_startup_scripts_and_still_runs_the_chosen_one() { + let _f = fresh(); + let dir = tmp_dir("safe"); + write(&dir, "a.jsx", "vc.log(1);"); + let mut s = session(&dir); + safe_mode::set_active(Some(safe_mode::Source::Flag)); + assert_eq!(s.startup_skip(), Some("safeMode")); + let r = s.execute("script.startup.run", &json!({"reason": "menu", "then": {"source": "vc.log(2);", "name": "chosen"}})).unwrap(); + assert_eq!(r["why"], "safeMode"); + assert_eq!(started(&s), ["chosen"]); +} + +#[test] +fn a_startup_script_the_safe_mode_choice_disabled_does_not_run() { + let _f = fresh(); + let dir = tmp_dir("disabled"); + let a = write(&dir, "a.jsx", "vc.log(1);"); + write(&dir, "b.jsx", "vc.log(1);"); + let mut s = session(&dir); + safe_mode::disable(safe_mode::Item::file(a.to_string_lossy())); + let r = s.execute("script.startup.run", &json!({"reason": "launch"})).unwrap(); + assert_eq!(names(&r["disabled"]), ["a.jsx"]); + assert_eq!(names(&r["ran"]), ["b.jsx"]); +} + +#[test] +fn a_failing_or_endless_startup_script_is_reported_and_the_next_and_the_chosen_script_run() { + let _f = fresh(); + let dir = tmp_dir("failing"); + write(&dir, "1 throws.jsx", "throw new Error('broken');"); + write(&dir, "2 endless.jsx", "for (;;) {}"); + write(&dir, "3 syntax.jsx", "var = ;"); + write(&dir, "4 fine.jsx", "vc.log(1);"); + let mut s = session(&dir); + let then = json!({"source": "vc.log('chosen');", "name": "chosen"}); + let r = s.execute("script.startup.run", &json!({"reason": "menu", "then": then, "maxFuel": 100000})).unwrap(); + let failed = r["failed"].as_array().unwrap(); + let failed_names: Vec<&str> = failed.iter().map(|f| f["name"].as_str().unwrap()).collect(); + assert_eq!(failed_names, ["1 throws.jsx", "2 endless.jsx", "3 syntax.jsx"]); + assert!(failed[0]["error"].as_str().unwrap().contains("broken"), "{failed:?}"); + assert_eq!(names(&r["ran"]), ["4 fine.jsx"]); + assert_eq!(r["then"]["ok"], true, "the chosen script runs after them"); + assert!(console(&s, "end").contains(&"ended: fuel".to_string()), "the endless one ran out of instructions"); +} + +#[test] +fn a_startup_script_larger_than_a_script_may_be_is_refused_unread() { + let _f = fresh(); + let dir = tmp_dir("large"); + let mut big = "//".to_string(); + big.push_str(&"x".repeat(vectorcraft_engine::script::MAX_SOURCE_BYTES)); + write(&dir, "big.jsx", &big); + let mut s = session(&dir); + let r = s.execute("script.startup.run", &json!({"reason": "launch"})).unwrap(); + assert_eq!(r["failed"], json!([{"name": "big.jsx", "error": vectorcraft_engine::cmd::scripts::TOO_LARGE}])); + assert!(console(&s, "error").iter().any(|l| l.contains(vectorcraft_engine::cmd::scripts::TOO_LARGE)), "the console names it"); +} + +#[test] +fn a_startup_script_cannot_start_another_startup_run() { + let _f = fresh(); + let dir = tmp_dir("nested"); + let text = + "try { vc.run('script.startup.run', {reason: 'menu', then: {source: 'vc.log(1);'}}); vc.log('nested'); } catch (e) { vc.log('refused'); }"; + write(&dir, "a.jsx", text); + let mut s = session(&dir); + let r = s.execute("script.startup.run", &json!({"reason": "launch"})).unwrap(); + assert_eq!(names(&r["ran"]), ["a.jsx"]); + assert_eq!(console(&s, "log"), ["refused"]); + assert_eq!(started(&s), ["a.jsx"]); +} + +#[test] +fn bad_parameters_are_refused() { + let _f = fresh(); + let dir = tmp_dir("params"); + let mut s = session(&dir); + for p in [ + json!({}), + json!({"reason": "boot"}), + json!({"reason": "menu", "then": "x.jsx"}), + json!({"reason": "launch", "maxFuel": 0}), + json!({"reason": "launch", "maxFuel": 1.5}), + ] { + assert!(s.execute("script.startup.run", &p).is_err(), "{p}"); + } +} + +#[test] +fn in_the_app_the_runs_are_queued_and_the_launch_marker_names_the_running_startup_script() { + let _f = fresh(); + let dir = tmp_dir("app"); + let launch = tmp_dir("app-launch"); + write(&dir, "a.jsx", "vc.log(1);"); + write(&dir, "b.jsx", "throw new Error('broken');"); + let mut big = "//".to_string(); + big.push_str(&"x".repeat(vectorcraft_engine::script::MAX_SOURCE_BYTES)); + write(&dir, "bb.jsx", &big); + write(&dir, "c.jsx", "vc.log(3);"); + assert!(safe_mode::begin_launch(&launch).is_none()); + let mut s = session(&dir); + s.script_frames = true; + let r = s.execute("script.startup.run", &json!({"reason": "menu", "then": {"source": "vc.log(4);", "name": "chosen"}})).unwrap(); + assert_eq!((r["running"].clone(), r["queued"].clone(), r["failed"].clone()), (json!(true), json!(5), json!([]))); + let marker = || { + let file = std::fs::read_dir(&launch) + .unwrap() + .filter_map(Result::ok) + .map(|e| e.path()) + .find(|p| p.extension().is_some_and(|e| e == "json")) + .unwrap(); + safe_mode::parse_marker(&std::fs::read(file).unwrap()) + }; + assert_eq!(marker().and_then(|i| i.name), Some("a.jsx".to_string()), "the marker names the running startup script"); + let mut results = vec![]; + for _ in 0..10_000 { + if !s.script_running() { + break; + } + if let Some(r) = s.script_pump() { + results.push(r.is_ok()); + } + } + assert!(!s.script_running()); + assert_eq!(results, [true, false, true, true], "each run reports as it ends"); + assert_eq!(started(&s), ["a.jsx", "b.jsx", "bb.jsx", "c.jsx", "chosen"]); + let too_large = vectorcraft_engine::cmd::scripts::TOO_LARGE.to_string(); + assert_eq!(s.take_startup_failures(), [("bb.jsx".to_string(), too_large)], "the one that could not start is kept for the app"); + assert!(s.take_startup_failures().is_empty()); + assert_eq!(marker(), None, "the marker names nothing once they have run"); +} + +#[test] +fn in_the_app_a_chosen_script_that_cannot_start_leaves_the_startup_scripts_result() { + let _f = fresh(); + let dir = tmp_dir("app-then"); + write(&dir, "a.jsx", "vc.log(1);"); + let mut s = session(&dir); + s.script_frames = true; + let missing = dir.join("gone").join("missing.jsx"); + let r = s.execute("script.startup.run", &json!({"reason": "menu", "then": {"path": missing.to_string_lossy()}})).unwrap(); + assert_eq!((r["running"].clone(), r["queued"].clone()), (json!(true), json!(2))); + let mut results = vec![]; + for _ in 0..10_000 { + if !s.script_running() { + break; + } + if let Some(r) = s.script_pump() { + results.push(r.is_ok()); + } + } + assert_eq!(results, [true], "the startup script's own result"); + let failures = s.take_startup_failures(); + assert_eq!(failures.iter().map(|(name, _)| name.as_str()).collect::>(), ["missing.jsx"]); +} + +#[test] +fn in_the_app_startup_scripts_that_cannot_start_are_in_the_reply() { + let _f = fresh(); + let dir = tmp_dir("app-unread"); + let mut big = "//".to_string(); + big.push_str(&"x".repeat(vectorcraft_engine::script::MAX_SOURCE_BYTES)); + write(&dir, "big.jsx", &big); + let mut s = session(&dir); + s.script_frames = true; + let r = s.execute("script.startup.run", &json!({"reason": "launch"})).unwrap(); + assert_eq!(r["running"], json!(false)); + assert_eq!(r["failed"], json!([{"name": "big.jsx", "error": vectorcraft_engine::cmd::scripts::TOO_LARGE}])); + assert_eq!(s.take_startup_failures().len(), 1, "and kept for the app's status bar"); +} diff --git a/crates/ui-egui/src/dialogs/safe_mode.rs b/crates/ui-egui/src/dialogs/safe_mode.rs index b26711c741..3a806e51ac 100644 --- a/crates/ui-egui/src/dialogs/safe_mode.rs +++ b/crates/ui-egui/src/dialogs/safe_mode.rs @@ -95,7 +95,8 @@ fn item_of(v: &Value) -> Item { } /// The choice's Disable and Continue (OK) or Start Normally: Safe Mode ends and the plug-ins load, -/// without the stopped one for Disable and Continue (kept off for later launches too). +/// without the stopped one for Disable and Continue (kept off for later launches too), then the +/// startup scripts run ([`crate::script_runs::run_at_launch`]), without a disabled one. fn confirm_stopped(app: &mut VectorcraftApp, d: &Dialog) -> Result { app.ui.dialog = None; app.ui.stopped_plugin = None; @@ -109,6 +110,8 @@ fn confirm_stopped(app: &mut VectorcraftApp, d: &Dialog) -> Result Result Result { } let script = d.fields.get("script").cloned().unwrap_or(Value::Null); app.ui.dialog = None; - app.run("script.run", script) + crate::script_runs::run_chosen(app, script) } fn growth_confirm(app: &mut VectorcraftApp, _: &Dialog) -> Result { diff --git a/crates/ui-egui/src/i18n/bg.tsv b/crates/ui-egui/src/i18n/bg.tsv index 167737554d..8bcb952c63 100644 --- a/crates/ui-egui/src/i18n/bg.tsv +++ b/crates/ui-egui/src/i18n/bg.tsv @@ -3205,6 +3205,7 @@ digits Malayalam Малаялам Drawing tools show a crosshair pointer instead of their icon; Caps Lock does the same while it is on. Инструментите за рисуване показват показалец във форма на кръст вместо иконата си; Caps Lock прави същото, докато е включен. Shows a tip when the pointer rests on a button or field that has one. Показва подсказка, когато показалецът спре върху бутон или поле, които имат такава. Shows a warning before a script you choose runs. Показва предупреждение, преди да се изпълни скрипт, който изберете. + Runs the scripts in the Startup Scripts folder when VectorCraft starts and before each script from File › Scripts; not in Safe Mode. Изпълнява скриптовете от папката Startup Scripts при стартиране на VectorCraft и преди всеки скрипт от Файл › Скриптове; не и в безопасен режим. Smooths the edges of artwork on the canvas. Изглажда ръбовете на графиката върху платното. Select › Same › Fill Color, Stroke Color and Fill & Stroke match only the same tint of a global or spot swatch, not any tint of it. „Селекция › Същото › Цвят на запълване“, „Цвят на щриха“ и „Запълване и щрих“ намират само същия нюанс на глобална или плътна мостра, а не всеки неин нюанс. Shows the Home screen when no document is open; off, the window stays empty until you click Home. Показва началния екран, когато няма отворен документ; ако е изключено, прозорецът остава празен, докато не щракнете „Начало“. @@ -4703,6 +4704,7 @@ axis Both И двете Run Script Изпълни скрипт Stop Script Спри скрипта Show External Script Warning Показвай предупреждение за външни скриптове + Run Startup Scripts Изпълнявай стартови скриптове A Script Is Running Изпълнява се скрипт Script Alert Известие от скрипт Script File Access Достъп на скрипт до файлове diff --git a/crates/ui-egui/src/i18n/bs.tsv b/crates/ui-egui/src/i18n/bs.tsv index a9d6e35ed8..16936c57cf 100644 --- a/crates/ui-egui/src/i18n/bs.tsv +++ b/crates/ui-egui/src/i18n/bs.tsv @@ -4692,6 +4692,7 @@ font-technology Variable Varijabilni Drawing tools show a crosshair pointer instead of their icon; Caps Lock does the same while it is on. Alati za crtanje prikazuju pokazivač u obliku krstića umjesto svoje ikone; Caps Lock čini isto dok je uključen. Shows a tip when the pointer rests on a button or field that has one. Prikazuje savjet kada se pokazivač zadrži na dugmetu ili polju koje ga ima. Shows a warning before a script you choose runs. Prikazuje upozorenje prije nego što se pokrene skripta koju odaberete. + Runs the scripts in the Startup Scripts folder when VectorCraft starts and before each script from File › Scripts; not in Safe Mode. Pokreće skripte iz mape Startup Scripts kada se VectorCraft pokrene i prije svake skripte iz Datoteka › Skripte; ne u sigurnom načinu rada. Smooths the edges of artwork on the canvas. Izglađuje rubove grafike na platnu. Select › Same › Fill Color, Stroke Color and Fill & Stroke match only the same tint of a global or spot swatch, not any tint of it. Odabir › Isto › Boja ispune, Boja poteza i Ispuna i potez pronalaze samo istu nijansu globalnog ili spot uzorka, a ne bilo koju njegovu nijansu. Shows the Home screen when no document is open; off, the window stays empty until you click Home. Prikazuje početni ekran kada nijedan dokument nije otvoren; kada je isključeno, prozor ostaje prazan dok ne kliknete Početna. @@ -5107,6 +5108,7 @@ imageTrace Outline Obris Run Script Pokreni skriptu Stop Script Zaustavi skriptu Show External Script Warning Prikaži upozorenje za vanjske skripte + Run Startup Scripts Pokreni skripte pri pokretanju A Script Is Running Skripta se izvršava Script Alert Upozorenje skripte Script File Access Pristup skripte datotekama diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index e4271f7926..9c5b633a50 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -4063,6 +4063,7 @@ digits Malayalam Malaiàlam Drawing tools show a crosshair pointer instead of their icon; Caps Lock does the same while it is on. Les eines de dibuix mostren un punter en creu en lloc de la seva icona; Bloq Maj fa el mateix mentre està activat. Shows a tip when the pointer rests on a button or field that has one. Mostra un consell quan el punter s’atura sobre un botó o un camp que en té. Shows a warning before a script you choose runs. Mostra un avís abans que s’executi un script que trieu. + Runs the scripts in the Startup Scripts folder when VectorCraft starts and before each script from File › Scripts; not in Safe Mode. Executa els scripts de la carpeta Startup Scripts quan s’inicia VectorCraft i abans de cada script de Fitxer › Scripts; no en mode segur. Smooths the edges of artwork on the canvas. Suavitza les vores de la il·lustració al llenç. Select › Same › Fill Color, Stroke Color and Fill & Stroke match only the same tint of a global or spot swatch, not any tint of it. Selecció › Igual › Color de farciment, Color del traç i Farciment i traç només coincideixen amb el mateix matís d’una mostra global o de tinta plana, no amb qualsevol matís seu. Shows the Home screen when no document is open; off, the window stays empty until you click Home. Mostra la pantalla d’inici quan no hi ha cap document obert; desactivada, la finestra queda buida fins que feu clic a Inici. @@ -6414,6 +6415,7 @@ digits Malayalam Malaiàlam Run Script Executa l'script Stop Script Atura l'script Show External Script Warning Mostra l'avís dels scripts externs + Run Startup Scripts Executa els scripts d’inici A Script Is Running S'està executant un script Script Alert Avís de l'script Script File Access Accés de l’script als fitxers diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index 488df173c3..82bc2d5fb6 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -4801,6 +4801,7 @@ font-technology Variable Variabilní Drawing tools show a crosshair pointer instead of their icon; Caps Lock does the same while it is on. Kreslicí nástroje zobrazí místo své ikony nitkový kříž; Caps Lock udělá totéž, dokud je zapnutý. Shows a tip when the pointer rests on a button or field that has one. Zobrazí tip, když ukazatel spočine na tlačítku nebo poli, které ho má. Shows a warning before a script you choose runs. Zobrazí upozornění před spuštěním skriptu, který zvolíte. + Runs the scripts in the Startup Scripts folder when VectorCraft starts and before each script from File › Scripts; not in Safe Mode. Spouští skripty ze složky Startup Scripts při spuštění aplikace VectorCraft a před každým skriptem z nabídky Soubor › Skripty; ne v nouzovém režimu. Smooths the edges of artwork on the canvas. Vyhladí okraje kresby na plátně. Select › Same › Fill Color, Stroke Color and Fill & Stroke match only the same tint of a global or spot swatch, not any tint of it. Výběr › Stejné › Barva výplně, Barva tahu a Výplň a tah najdou jen stejný odstín globálního nebo přímého vzorku, ne libovolný jeho odstín. Shows the Home screen when no document is open; off, the window stays empty until you click Home. Zobrazí domovskou obrazovku, když není otevřený žádný dokument; když je vypnuto, okno zůstane prázdné, dokud neklepnete na Domů. @@ -5222,6 +5223,7 @@ imageTrace Outline Obrys Run Script Spustit skript Stop Script Zastavit skript Show External Script Warning Zobrazit upozornění u externích skriptů + Run Startup Scripts Spouštět spouštěcí skripty A Script Is Running Běží skript Script Alert Upozornění skriptu Script File Access Přístup skriptu k souborům diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index 302ab6aa69..54f430fe98 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -7249,6 +7249,7 @@ font-technology Variable Variable Drawing tools show a crosshair pointer instead of their icon; Caps Lock does the same while it is on. Tegneværktøjer viser en trådkorsmarkør i stedet for deres ikon; Caps Lock gør det samme, mens den er slået til. Shows a tip when the pointer rests on a button or field that has one. Viser et tip, når markøren hviler på en knap eller et felt, der har et. Shows a warning before a script you choose runs. Viser en advarsel, før et script, du vælger, køres. + Runs the scripts in the Startup Scripts folder when VectorCraft starts and before each script from File › Scripts; not in Safe Mode. Kører scripts i mappen Startup Scripts, når VectorCraft starter, og før hvert script fra Filer › Scripter; ikke i sikker tilstand. Smooths the edges of artwork on the canvas. Udglatter kanterne på grafikken på lærredet. Select › Same › Fill Color, Stroke Color and Fill & Stroke match only the same tint of a global or spot swatch, not any tint of it. Markér › Samme › Fyldfarve, Stregfarve og Fyld og streg finder kun samme nuance af en global farveprøve eller staffagefarve, ikke en hvilken som helst nuance af den. Shows the Home screen when no document is open; off, the window stays empty until you click Home. Viser startskærmen, når intet dokument er åbent; når den er slået fra, forbliver vinduet tomt, indtil du klikker på Home. @@ -7652,6 +7653,7 @@ imageTrace Outline Kontur Run Script Kør script Stop Script Stop script Show External Script Warning Vis advarsel om eksterne scripts + Run Startup Scripts Kør startscripts A Script Is Running Et script kører Script Alert Scriptadvarsel Script File Access Scriptadgang til filer diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index 9482345f18..7786ab6c1f 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -3275,6 +3275,7 @@ digits Malayalam Malayalam Drawing tools show a crosshair pointer instead of their icon; Caps Lock does the same while it is on. Zeichenwerkzeuge zeigen statt ihres Symbols ein Fadenkreuz; die Feststelltaste bewirkt dasselbe, solange sie aktiv ist. Shows a tip when the pointer rests on a button or field that has one. Zeigt einen Tipp an, wenn der Zeiger auf einer Schaltfläche oder einem Feld mit Tipp ruht. Shows a warning before a script you choose runs. Zeigt eine Warnung an, bevor ein von Ihnen gewähltes Skript ausgeführt wird. + Runs the scripts in the Startup Scripts folder when VectorCraft starts and before each script from File › Scripts; not in Safe Mode. Führt die Skripte im Ordner Startup Scripts beim Start von VectorCraft und vor jedem Skript aus Datei › Skripte aus; nicht im abgesicherten Modus. Smooths the edges of artwork on the canvas. Glättet die Kanten des Bildmaterials auf der Arbeitsfläche. Select › Same › Fill Color, Stroke Color and Fill & Stroke match only the same tint of a global or spot swatch, not any tint of it. „Auswahl › Gleich › Flächenfarbe“, „Konturfarbe“ und „Fläche und Kontur“ finden nur denselben Farbton eines globalen oder Volltonfarbfelds, nicht jeden Farbton davon. Shows the Home screen when no document is open; off, the window stays empty until you click Home. Zeigt den Startbildschirm, wenn kein Dokument geöffnet ist; ist die Option aus, bleibt das Fenster leer, bis Sie auf „Start“ klicken. @@ -4807,6 +4808,7 @@ theme Appearance Erscheinungsbild Run Script Skript ausführen Stop Script Skript stoppen Show External Script Warning Warnung bei externen Skripten anzeigen + Run Startup Scripts Startskripte ausführen A Script Is Running Ein Skript wird ausgeführt Script Alert Skriptmeldung Script File Access Dateizugriff des Skripts diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index 434d0cc0b8..4dc97a67b5 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -2611,6 +2611,7 @@ axis Both Και τα δύο Run Script Εκτέλεση σεναρίου Stop Script Διακοπή σεναρίου Show External Script Warning Εμφάνιση προειδοποίησης για εξωτερικά σενάρια + Run Startup Scripts Εκτέλεση σεναρίων εκκίνησης A Script Is Running Εκτελείται ένα σενάριο Script Alert Ειδοποίηση σεναρίου Script File Access Πρόσβαση σεναρίου σε αρχεία @@ -4128,6 +4129,7 @@ digits Malayalam Μαλαγιάλαμ Drawing tools show a crosshair pointer instead of their icon; Caps Lock does the same while it is on. Τα εργαλεία σχεδίασης εμφανίζουν δείκτη σταυρονήματος αντί για το εικονίδιό τους· το Caps Lock κάνει το ίδιο όσο είναι ενεργό. Shows a tip when the pointer rests on a button or field that has one. Εμφανίζει μια συμβουλή όταν ο δείκτης σταματά πάνω σε κουμπί ή πεδίο που έχει. Shows a warning before a script you choose runs. Εμφανίζει μια προειδοποίηση πριν εκτελεστεί ένα σενάριο που επιλέγετε. + Runs the scripts in the Startup Scripts folder when VectorCraft starts and before each script from File › Scripts; not in Safe Mode. Εκτελεί τα σενάρια του φακέλου Startup Scripts κατά την εκκίνηση του VectorCraft και πριν από κάθε σενάριο από Αρχείο › Δέσμες ενεργειών· όχι σε ασφαλή λειτουργία. Smooths the edges of artwork on the canvas. Εξομαλύνει τα άκρα του γραφικού στον καμβά. Select › Same › Fill Color, Stroke Color and Fill & Stroke match only the same tint of a global or spot swatch, not any tint of it. Τα Επιλογή › Ίδιο › Χρώμα γεμίσματος, Χρώμα περιγράμματος και Γέμισμα και περίγραμμα βρίσκουν μόνο την ίδια απόχρωση ενός καθολικού ή σημειακού δείγματος, όχι οποιαδήποτε απόχρωσή του. Shows the Home screen when no document is open; off, the window stays empty until you click Home. Εμφανίζει την αρχική οθόνη όταν δεν είναι ανοιχτό κανένα έγγραφο· όταν είναι ανενεργό, το παράθυρο μένει κενό μέχρι να κάνετε κλικ στην Αρχική οθόνη. diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index 3f83e928e4..5a3b001197 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -3311,6 +3311,7 @@ digits Malayalam Malayálam Drawing tools show a crosshair pointer instead of their icon; Caps Lock does the same while it is on. Las herramientas de dibujo muestran un puntero en cruz en lugar de su icono; Bloq Mayús hace lo mismo mientras está activado. Shows a tip when the pointer rests on a button or field that has one. Muestra una sugerencia cuando el puntero se detiene sobre un botón o campo que la tiene. Shows a warning before a script you choose runs. Muestra una advertencia antes de que se ejecute un script que elija. + Runs the scripts in the Startup Scripts folder when VectorCraft starts and before each script from File › Scripts; not in Safe Mode. Ejecuta los scripts de la carpeta Startup Scripts al iniciar VectorCraft y antes de cada script de Archivo › Scripts; no en modo seguro. Smooths the edges of artwork on the canvas. Suaviza los bordes de la ilustración en el lienzo. Select › Same › Fill Color, Stroke Color and Fill & Stroke match only the same tint of a global or spot swatch, not any tint of it. Selección › Igual › Color de relleno, Color de trazo y Relleno y trazo solo coinciden con el mismo matiz de una muestra global o de tinta plana, no con cualquier matiz de ella. Shows the Home screen when no document is open; off, the window stays empty until you click Home. Muestra la pantalla de inicio cuando no hay ningún documento abierto; desactivada, la ventana queda vacía hasta que hace clic en Inicio. @@ -4886,6 +4887,7 @@ axis Both Ambos Run Script Ejecutar script Stop Script Detener script Show External Script Warning Mostrar advertencia de scripts externos + Run Startup Scripts Ejecutar scripts de inicio A Script Is Running Se está ejecutando un script Script Alert Aviso del script Script File Access Acceso del script a archivos diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index a4d85b23e8..b6aec2d644 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -4711,6 +4711,7 @@ font-technology Variable Muuttuvat Drawing tools show a crosshair pointer instead of their icon; Caps Lock does the same while it is on. Piirtotyökalut näyttävät kuvakkeensa sijaan ristikko-osoittimen; Caps Lock tekee saman, kun se on käytössä. Shows a tip when the pointer rests on a button or field that has one. Näyttää vihjeen, kun osoitin pysähtyy painikkeen tai kentän päälle, jolla on vihje. Shows a warning before a script you choose runs. Näyttää varoituksen ennen kuin valitsemasi komentosarja suoritetaan. + Runs the scripts in the Startup Scripts folder when VectorCraft starts and before each script from File › Scripts; not in Safe Mode. Suorittaa Startup Scripts -kansion komentosarjat, kun VectorCraft käynnistyy, ja ennen jokaista komentosarjaa valikosta Tiedosto › Komentosarjat; ei vikasietotilassa. Smooths the edges of artwork on the canvas. Pehmentää piirtopinnalla olevan grafiikan reunat. Select › Same › Fill Color, Stroke Color and Fill & Stroke match only the same tint of a global or spot swatch, not any tint of it. Valinta › Sama › Täyttöväri, Viivan väri sekä Täyttö ja viiva löytävät vain globaalin tai spottivärimallin saman sävyn, eivät mitä tahansa sen sävyä. Shows the Home screen when no document is open; off, the window stays empty until you click Home. Näyttää aloitusnäytön, kun yhtään asiakirjaa ei ole auki; kun asetus ei ole käytössä, ikkuna pysyy tyhjänä, kunnes napsautat Aloitus. @@ -5127,6 +5128,7 @@ imageTrace Outline Ääriviiva Run Script Suorita komentosarja Stop Script Pysäytä komentosarja Show External Script Warning Näytä ulkoisten komentosarjojen varoitus + Run Startup Scripts Suorita käynnistyskomentosarjat A Script Is Running Komentosarja on käynnissä Script Alert Komentosarjan ilmoitus Script File Access Komentosarjan tiedostojen käyttö diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 8f56486157..e0bdcf7625 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -3299,6 +3299,7 @@ digits Malayalam Malayalam Drawing tools show a crosshair pointer instead of their icon; Caps Lock does the same while it is on. Les outils de dessin affichent un pointeur en croix au lieu de leur icône. Le Verrouillage majuscules fait de même tant qu’il est activé. Shows a tip when the pointer rests on a button or field that has one. Affiche une info-bulle quand le pointeur s’arrête sur un bouton ou un champ qui en a une. Shows a warning before a script you choose runs. Affiche un avertissement avant l’exécution d’un script que vous choisissez. + Runs the scripts in the Startup Scripts folder when VectorCraft starts and before each script from File › Scripts; not in Safe Mode. Exécute les scripts du dossier Startup Scripts au démarrage de VectorCraft et avant chaque script de Fichier › Scripts. Ne s’applique pas en mode sans échec. Smooths the edges of artwork on the canvas. Lisse les bords des illustrations sur la zone de travail. Select › Same › Fill Color, Stroke Color and Fill & Stroke match only the same tint of a global or spot swatch, not any tint of it. Sélection › Identique › Couleur de fond, Couleur du contour et Fond et contour ne retiennent que la même teinte d’une nuance globale ou d’une couleur d’accompagnement, et non toutes ses teintes. Shows the Home screen when no document is open; off, the window stays empty until you click Home. Affiche l’écran d’accueil quand aucun document n’est ouvert. Désactivée, la fenêtre reste vide jusqu’à ce que vous cliquiez sur Accueil. @@ -4868,6 +4869,7 @@ axis Both Les deux Run Script Exécuter le script Stop Script Arrêter le script Show External Script Warning Afficher l’avertissement des scripts externes + Run Startup Scripts Exécuter les scripts de démarrage A Script Is Running Un script est en cours d’exécution Script Alert Alerte de script Script File Access Accès du script aux fichiers diff --git a/crates/ui-egui/src/i18n/gu.tsv b/crates/ui-egui/src/i18n/gu.tsv index 0bb7c9b71f..b72a77a4d6 100644 --- a/crates/ui-egui/src/i18n/gu.tsv +++ b/crates/ui-egui/src/i18n/gu.tsv @@ -3366,6 +3366,7 @@ arrowhead Feather પીંછું Drawing tools show a crosshair pointer instead of their icon; Caps Lock does the same while it is on. ડ્રોઇંગ ટૂલ્સ તેમના આઇકનને બદલે ક્રોસહેર પોઇન્ટર બતાવે છે; Caps Lock ચાલુ હોય ત્યારે પણ આવું જ થાય છે. Shows a tip when the pointer rests on a button or field that has one. ટિપ ધરાવતા બટન કે ફીલ્ડ પર પોઇન્ટર અટકે ત્યારે ટિપ બતાવે છે. Shows a warning before a script you choose runs. તમે પસંદ કરેલી સ્ક્રિપ્ટ ચાલે તે પહેલાં ચેતવણી બતાવે છે. + Runs the scripts in the Startup Scripts folder when VectorCraft starts and before each script from File › Scripts; not in Safe Mode. VectorCraft શરૂ થાય ત્યારે અને ફાઇલ › સ્ક્રિપ્ટ્સમાંથી દરેક સ્ક્રિપ્ટ પહેલાં Startup Scripts ફોલ્ડરની સ્ક્રિપ્ટ્સ ચલાવે છે; સેફ મોડમાં નહીં. Smooths the edges of artwork on the canvas. કેનવાસ પરના આર્ટવર્કની કિનારીઓ સુંવાળી કરે છે. Select › Same › Fill Color, Stroke Color and Fill & Stroke match only the same tint of a global or spot swatch, not any tint of it. પસંદ કરો › સમાન › ભરવાનો રંગ, સ્ટ્રોક રંગ અને ભરો અને સ્ટ્રોક ફક્ત ગ્લોબલ કે સ્પોટ સ્વૉચના એ જ ટિન્ટ સાથે મેળ ખાય છે, તેના કોઈપણ ટિન્ટ સાથે નહીં. Shows the Home screen when no document is open; off, the window stays empty until you click Home. કોઈ દસ્તાવેજ ખુલ્લો ન હોય ત્યારે હોમ સ્ક્રીન બતાવે છે; બંધ હોય ત્યારે તમે હોમ પર ક્લિક ન કરો ત્યાં સુધી વિન્ડો ખાલી રહે છે. @@ -3979,6 +3980,7 @@ arrowhead Feather પીંછું Show East Asian Options પૂર્વ એશિયન વિકલ્પો બતાવો Show Edges કિનારીઓ બતાવો Show External Script Warning બાહ્ય સ્ક્રિપ્ટ ચેતવણી બતાવો + Run Startup Scripts સ્ટાર્ટઅપ સ્ક્રિપ્ટ્સ ચલાવો Show Find Field શોધ ફીલ્ડ બતાવો Show Font Height Options ફોન્ટ ઊંચાઈ વિકલ્પો બતાવો Show Font Names in English ફોન્ટ નામો અંગ્રેજીમાં બતાવો diff --git a/crates/ui-egui/src/i18n/hi.tsv b/crates/ui-egui/src/i18n/hi.tsv index e9509d9202..f2cb9a0afe 100644 --- a/crates/ui-egui/src/i18n/hi.tsv +++ b/crates/ui-egui/src/i18n/hi.tsv @@ -4694,6 +4694,7 @@ arrowhead Feather पंख Drawing tools show a crosshair pointer instead of their icon; Caps Lock does the same while it is on. ड्रॉइंग टूल अपने आइकन की जगह क्रॉसहेयर पॉइंटर दिखाते हैं; Caps Lock चालू रहने पर भी यही होता है। Shows a tip when the pointer rests on a button or field that has one. जब पॉइंटर टिप वाले किसी बटन या फ़ील्ड पर रुकता है, तब टिप दिखाता है। Shows a warning before a script you choose runs. आपकी चुनी गई स्क्रिप्ट चलने से पहले चेतावनी दिखाता है। + Runs the scripts in the Startup Scripts folder when VectorCraft starts and before each script from File › Scripts; not in Safe Mode. VectorCraft शुरू होने पर और फ़ाइल › स्क्रिप्ट्स की हर स्क्रिप्ट से पहले Startup Scripts फ़ोल्डर की स्क्रिप्ट चलाता है; सुरक्षित मोड में नहीं। Smooths the edges of artwork on the canvas. कैनवास पर आर्टवर्क के किनारों को चिकना करता है। Select › Same › Fill Color, Stroke Color and Fill & Stroke match only the same tint of a global or spot swatch, not any tint of it. सिलेक्ट › समान › फ़िल रंग, स्ट्रोक रंग और फ़िल व स्ट्रोक केवल ग्लोबल या स्पॉट स्वॉच के उसी टिंट से मेल खाते हैं, उसके किसी भी टिंट से नहीं। Shows the Home screen when no document is open; off, the window stays empty until you click Home. कोई डॉक्यूमेंट खुला न होने पर होम स्क्रीन दिखाता है; बंद होने पर विंडो तब तक खाली रहती है जब तक आप होम पर क्लिक नहीं करते। @@ -7560,6 +7561,7 @@ arrowhead Feather पंख Run Script स्क्रिप्ट चलाएँ Stop Script स्क्रिप्ट रोकें Show External Script Warning बाहरी स्क्रिप्ट की चेतावनी दिखाएँ + Run Startup Scripts स्टार्टअप स्क्रिप्ट चलाएँ A Script Is Running एक स्क्रिप्ट चल रही है Script Alert स्क्रिप्ट सूचना Script File Access स्क्रिप्ट की फ़ाइल पहुँच diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index 87f050ef0d..aa97447796 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -3899,6 +3899,7 @@ mark-style Japanese Japán Drawing tools show a crosshair pointer instead of their icon; Caps Lock does the same while it is on. A rajzeszközök az ikonjuk helyett célkeresztes mutatót jelenítenek meg; a Caps Lock bekapcsolva ugyanezt teszi. Shows a tip when the pointer rests on a button or field that has one. Tippet jelenít meg, ha a mutató olyan gombon vagy mezőn áll meg, amelyhez tartozik tipp. Shows a warning before a script you choose runs. Figyelmeztetést jelenít meg egy kiválasztott parancsfájl futása előtt. + Runs the scripts in the Startup Scripts folder when VectorCraft starts and before each script from File › Scripts; not in Safe Mode. A VectorCraft indulásakor és a Fájl › Szkriptek menü minden parancsfájlja előtt futtatja a Startup Scripts mappa parancsfájljait; csökkentett módban nem. Smooths the edges of artwork on the canvas. Kisimítja a grafika széleit a vásznon. Select › Same › Fill Color, Stroke Color and Fill & Stroke match only the same tint of a global or spot swatch, not any tint of it. A Kijelölés › Azonos › Kitöltőszín, Körvonalszín és Kitöltés és körvonal csak egy globális vagy direkt színminta azonos árnyalatát találja meg, nem bármely árnyalatát. Shows the Home screen when no document is open; off, the window stays empty until you click Home. Megjeleníti a kezdőképernyőt, ha nincs megnyitott dokumentum; kikapcsolva az ablak üres marad, amíg a Kezdőképernyő gombra nem kattint. @@ -5739,6 +5740,7 @@ imageTrace Outline Körvonal Run Script Parancsfájl futtatása Stop Script Parancsfájl leállítása Show External Script Warning Figyelmeztetés külső parancsfájlok előtt + Run Startup Scripts Indítási parancsfájlok futtatása A Script Is Running Egy parancsfájl fut Script Alert Parancsfájl-értesítés Script File Access Parancsfájl fájlhozzáférése diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index 924d3d80b5..21908fda55 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -5115,6 +5115,7 @@ font-technology Variable Variabel Drawing tools show a crosshair pointer instead of their icon; Caps Lock does the same while it is on. Alat gambar menampilkan penunjuk silang sebagai pengganti ikonnya; Caps Lock melakukan hal yang sama selama aktif. Shows a tip when the pointer rests on a button or field that has one. Menampilkan tip saat penunjuk berhenti di atas tombol atau bidang yang memilikinya. Shows a warning before a script you choose runs. Menampilkan peringatan sebelum skrip yang Anda pilih dijalankan. + Runs the scripts in the Startup Scripts folder when VectorCraft starts and before each script from File › Scripts; not in Safe Mode. Menjalankan skrip di folder Startup Scripts saat VectorCraft dimulai dan sebelum setiap skrip dari Berkas › Skrip; tidak dalam mode aman. Smooths the edges of artwork on the canvas. Menghaluskan tepi karya seni di kanvas. Select › Same › Fill Color, Stroke Color and Fill & Stroke match only the same tint of a global or spot swatch, not any tint of it. Seleksi › Sama › Warna isian, Warna stroke, dan Isian & stroke hanya mencocokkan tint yang sama dari swatch global atau spot, bukan sembarang tint-nya. Shows the Home screen when no document is open; off, the window stays empty until you click Home. Menampilkan layar Home saat tidak ada dokumen yang terbuka; saat nonaktif, jendela tetap kosong sampai Anda mengklik Home. @@ -5518,6 +5519,7 @@ imageTrace Outline Kontur Run Script Jalankan Skrip Stop Script Hentikan Skrip Show External Script Warning Tampilkan Peringatan Skrip Eksternal + Run Startup Scripts Jalankan Skrip Awal A Script Is Running Skrip Sedang Berjalan Script Alert Peringatan Skrip Script File Access Akses Berkas Skrip diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index 5f47e3f117..d57067bbdc 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -3360,6 +3360,7 @@ digits Malayalam Malayalam Drawing tools show a crosshair pointer instead of their icon; Caps Lock does the same while it is on. Gli strumenti di disegno mostrano un puntatore a croce invece della loro icona; Bloc Maiusc fa lo stesso finché è attivo. Shows a tip when the pointer rests on a button or field that has one. Mostra un suggerimento quando il puntatore si ferma su un pulsante o un campo che ne ha uno. Shows a warning before a script you choose runs. Mostra un avviso prima che venga eseguito uno script che scegli. + Runs the scripts in the Startup Scripts folder when VectorCraft starts and before each script from File › Scripts; not in Safe Mode. Esegue gli script della cartella Startup Scripts all’avvio di VectorCraft e prima di ogni script di File › Script; non in modalità provvisoria. Smooths the edges of artwork on the canvas. Smussa i bordi della grafica nell'area di lavoro. Select › Same › Fill Color, Stroke Color and Fill & Stroke match only the same tint of a global or spot swatch, not any tint of it. Selezione › Uguale › Colore riempimento, Colore traccia e Riempimento e traccia trovano solo la stessa tinta di un campione globale o di un colore spot, non qualsiasi sua tinta. Shows the Home screen when no document is open; off, the window stays empty until you click Home. Mostra la schermata Home quando nessun documento è aperto; se disattivata, la finestra resta vuota finché non fai clic su Home. @@ -4945,6 +4946,7 @@ axis Both Entrambi Run Script Esegui script Stop Script Interrompi script Show External Script Warning Mostra avviso per gli script esterni + Run Startup Scripts Esegui script di avvio A Script Is Running È in esecuzione uno script Script Alert Avviso dello script Script File Access Accesso dello script ai file diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index 9a1b5f6354..76f1a6404b 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -3328,6 +3328,7 @@ mark-style Japanese 日本式 Drawing tools show a crosshair pointer instead of their icon; Caps Lock does the same while it is on. 描画ツールのポインターをアイコンではなく十字にします。Caps Lock がオンの間も同じになります。 Shows a tip when the pointer rests on a button or field that has one. ヒントのあるボタンやフィールドにポインターを置くとヒントを表示します。 Shows a warning before a script you choose runs. 選んだスクリプトを実行する前に警告を表示します。 + Runs the scripts in the Startup Scripts folder when VectorCraft starts and before each script from File › Scripts; not in Safe Mode. VectorCraft の起動時と、ファイル › スクリプト のスクリプトを実行する前に、Startup Scripts フォルダーのスクリプトを実行します。セーフモードでは実行しません。 Smooths the edges of artwork on the canvas. カンバス上のアートワークの縁を滑らかにします。 Select › Same › Fill Color, Stroke Color and Fill & Stroke match only the same tint of a global or spot swatch, not any tint of it. 選択 › 共通 › カラー (塗り)、カラー (線)、塗りと線は、グローバルスウォッチまたは特色スウォッチの同じ濃度だけを選び、ほかの濃度は選びません。 Shows the Home screen when no document is open; off, the window stays empty until you click Home. ドキュメントが開いていないときにホーム画面を表示します。オフのときは、ホームをクリックするまでウィンドウは空のままです。 @@ -5771,6 +5772,7 @@ variable-list-end {0}, {1} {0}、{1} Run Script スクリプトを実行 Stop Script スクリプトを停止 Show External Script Warning 外部スクリプトの警告を表示 + Run Startup Scripts スタートアップスクリプトを実行 A Script Is Running スクリプトの実行中 Script Alert スクリプトの通知 Script File Access スクリプトのファイルアクセス diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index 8eeacee621..7cb1972a56 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -6502,6 +6502,7 @@ font-technology Variable ცვლადი Drawing tools show a crosshair pointer instead of their icon; Caps Lock does the same while it is on. სახატავი ხელსაწყოები ხატულის ნაცვლად ჯვრისებრ მაჩვენებელს აჩვენებენ; Caps Lock იგივეს აკეთებს, სანამ ჩართულია. Shows a tip when the pointer rests on a button or field that has one. აჩვენებს მინიშნებას, როცა მაჩვენებელი ჩერდება ღილაკზე ან ველზე, რომელსაც ის აქვს. Shows a warning before a script you choose runs. აჩვენებს გაფრთხილებას თქვენ მიერ არჩეული სკრიპტის გაშვებამდე. + Runs the scripts in the Startup Scripts folder when VectorCraft starts and before each script from File › Scripts; not in Safe Mode. უშვებს Startup Scripts საქაღალდის სკრიპტებს VectorCraft-ის გაშვებისას და ფაილი › სკრიპტები მენიუს ყოველი სკრიპტის წინ; უსაფრთხო რეჟიმში არა. Smooths the edges of artwork on the canvas. ტილოზე ნახატის კიდეებს აგლუვებს. Select › Same › Fill Color, Stroke Color and Fill & Stroke match only the same tint of a global or spot swatch, not any tint of it. მონიშვნა › იგივე › შევსების ფერი, კონტურის ფერი და შევსება და კონტური პოულობს გლობალური ან სპოტ-ფერის ნიმუშის მხოლოდ იმავე ტონირებას და არა მის ნებისმიერ ტონირებას. Shows the Home screen when no document is open; off, the window stays empty until you click Home. აჩვენებს საწყის ეკრანს, როცა არცერთი დოკუმენტი არ არის გახსნილი; გამორთვისას ფანჯარა ცარიელი რჩება, „საწყის ეკრანზე“ დაწკაპუნებამდე. @@ -8440,6 +8441,7 @@ imageTrace Outline კონტური List Installed Scripts დაინსტალირებული სკრიპტების სია Stop Script სკრიპტის შეჩერება Show External Script Warning გარე სკრიპტის გაფრთხილების ჩვენება + Run Startup Scripts გაშვების სკრიპტების შესრულება A Script Is Running სკრიპტი მუშაობს Script Alert სკრიპტის შეტყობინება Script File Access სკრიპტის წვდომა ფაილებზე diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index 57e0b8be10..f1087286ff 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -3317,6 +3317,7 @@ mark-style Japanese 일본식 Drawing tools show a crosshair pointer instead of their icon; Caps Lock does the same while it is on. 그리기 도구의 포인터를 아이콘 대신 십자선으로 표시합니다. Caps Lock이 켜져 있는 동안에도 같습니다. Shows a tip when the pointer rests on a button or field that has one. 도움말이 있는 버튼이나 필드에 포인터를 올려 두면 도움말을 표시합니다. Shows a warning before a script you choose runs. 선택한 스크립트를 실행하기 전에 경고를 표시합니다. + Runs the scripts in the Startup Scripts folder when VectorCraft starts and before each script from File › Scripts; not in Safe Mode. VectorCraft가 시작될 때와 파일 › 스크립트의 각 스크립트 전에 Startup Scripts 폴더의 스크립트를 실행합니다. 안전 모드에서는 실행하지 않습니다. Smooths the edges of artwork on the canvas. 캔버스에 있는 아트웍의 가장자리를 매끄럽게 표시합니다. Select › Same › Fill Color, Stroke Color and Fill & Stroke match only the same tint of a global or spot swatch, not any tint of it. 선택 › 동일 › 칠 색상, 선 색상, 칠 및 선은 전역 또는 별색 견본의 같은 색조만 찾고, 다른 색조는 찾지 않습니다. Shows the Home screen when no document is open; off, the window stays empty until you click Home. 열린 문서가 없을 때 홈 화면을 표시합니다. 끄면 홈을 클릭할 때까지 창이 비어 있습니다. @@ -5700,6 +5701,7 @@ variable-list-end {0}, {1} {0} 및 {1} Run Script 스크립트 실행 Stop Script 스크립트 중지 Show External Script Warning 외부 스크립트 경고 표시 + Run Startup Scripts 시작 스크립트 실행 A Script Is Running 스크립트 실행 중 Script Alert 스크립트 알림 Script File Access 스크립트 파일 접근 diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index 5ed5cdc3e0..0860fc50c7 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -5115,6 +5115,7 @@ font-technology Variable Variabel Drawing tools show a crosshair pointer instead of their icon; Caps Lock does the same while it is on. Tekengereedschappen tonen een kruisdraadaanwijzer in plaats van hun pictogram; Caps Lock doet hetzelfde zolang die aan staat. Shows a tip when the pointer rests on a button or field that has one. Toont een tip wanneer de aanwijzer stilstaat op een knop of veld dat er een heeft. Shows a warning before a script you choose runs. Toont een waarschuwing voordat een script dat u kiest wordt uitgevoerd. + Runs the scripts in the Startup Scripts folder when VectorCraft starts and before each script from File › Scripts; not in Safe Mode. Voert de scripts in de map Startup Scripts uit wanneer VectorCraft start en vóór elk script uit Bestand › Scripts; niet in de veilige modus. Smooths the edges of artwork on the canvas. Maakt de randen van illustraties op het canvas vloeiend. Select › Same › Fill Color, Stroke Color and Fill & Stroke match only the same tint of a global or spot swatch, not any tint of it. Selecteren › Zelfde › Vulkleur, Contourkleur en Vulling en contour vinden alleen dezelfde tint van een globaal of steunkleurstaal, niet elke tint ervan. Shows the Home screen when no document is open; off, the window stays empty until you click Home. Toont het startscherm wanneer er geen document open is; uitgeschakeld blijft het venster leeg totdat u op Home klikt. @@ -5518,6 +5519,7 @@ imageTrace Outline Contour Run Script Script uitvoeren Stop Script Script stoppen Show External Script Warning Waarschuwing voor externe scripts tonen + Run Startup Scripts Opstartscripts uitvoeren A Script Is Running Er wordt een script uitgevoerd Script Alert Scriptmelding Script File Access Bestandstoegang van script diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index 74029133dc..3907186f99 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -4644,6 +4644,7 @@ font-technology Variable Zmienne Drawing tools show a crosshair pointer instead of their icon; Caps Lock does the same while it is on. Narzędzia do rysowania pokazują wskaźnik w kształcie krzyżyka zamiast swojej ikony; Caps Lock działa tak samo, dopóki jest włączony. Shows a tip when the pointer rests on a button or field that has one. Pokazuje wskazówkę, gdy wskaźnik zatrzyma się na przycisku lub polu, które ją ma. Shows a warning before a script you choose runs. Pokazuje ostrzeżenie przed uruchomieniem wybranego skryptu. + Runs the scripts in the Startup Scripts folder when VectorCraft starts and before each script from File › Scripts; not in Safe Mode. Uruchamia skrypty z folderu Startup Scripts przy starcie programu VectorCraft i przed każdym skryptem z menu Plik › Skrypty; nie w trybie awaryjnym. Smooths the edges of artwork on the canvas. Wygładza krawędzie kompozycji na obszarze roboczym. Select › Same › Fill Color, Stroke Color and Fill & Stroke match only the same tint of a global or spot swatch, not any tint of it. Zaznacz › Taki sam › Kolor wypełnienia, Kolor obrysu oraz Wypełnienie i obrys dopasowują tylko ten sam odcień globalnej lub dodatkowej próbki, a nie dowolny jej odcień. Shows the Home screen when no document is open; off, the window stays empty until you click Home. Pokazuje stronę startową, gdy nie jest otwarty żaden dokument; po wyłączeniu okno pozostaje puste, dopóki nie klikniesz Strona startowa. @@ -5050,6 +5051,7 @@ imageTrace Outline Kontur Run Script Uruchom skrypt Stop Script Zatrzymaj skrypt Show External Script Warning Pokazuj ostrzeżenie o skryptach zewnętrznych + Run Startup Scripts Uruchamiaj skrypty startowe A Script Is Running Skrypt jest uruchomiony Script Alert Komunikat skryptu Script File Access Dostęp skryptu do plików diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index a1747af0b2..92faaa025b 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -2766,6 +2766,7 @@ digits Malayalam Malaiala Drawing tools show a crosshair pointer instead of their icon; Caps Lock does the same while it is on. As ferramentas de desenho mostram um ponteiro em cruz em vez do ícone; o Caps Lock faz o mesmo enquanto está ativado. Shows a tip when the pointer rests on a button or field that has one. Mostra uma dica quando o ponteiro para sobre um botão ou campo que tem uma. Shows a warning before a script you choose runs. Mostra um aviso antes de executar um script que você escolher. + Runs the scripts in the Startup Scripts folder when VectorCraft starts and before each script from File › Scripts; not in Safe Mode. Executa os scripts da pasta Startup Scripts quando o VectorCraft inicia e antes de cada script de Arquivo › Scripts; não no Modo de Segurança. Smooths the edges of artwork on the canvas. Suaviza as bordas da arte na tela. Select › Same › Fill Color, Stroke Color and Fill & Stroke match only the same tint of a global or spot swatch, not any tint of it. Seleção › Igual › Cor de Preenchimento, Cor do Traçado e Preenchimento e Traçado encontram apenas o mesmo tom de uma amostra global ou de cor especial, não qualquer tom dela. Shows the Home screen when no document is open; off, the window stays empty until you click Home. Mostra a tela Início quando nenhum documento está aberto; desativada, a janela fica vazia até você clicar em Início. @@ -6089,6 +6090,7 @@ variable-list-end {0}, {1} {0} e {1} Run Script Executar script Stop Script Parar script Show External Script Warning Mostrar aviso de scripts externos + Run Startup Scripts Executar scripts de inicialização A Script Is Running Um script está em execução Script Alert Alerta do script Script File Access Acesso do script a arquivos diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index ca0c8d5145..cde0c8d12a 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -3342,6 +3342,7 @@ digits Malayalam Малаялам Drawing tools show a crosshair pointer instead of their icon; Caps Lock does the same while it is on. Инструменты рисования показывают указатель-перекрестие вместо своего значка; Caps Lock делает то же самое, пока он включён. Shows a tip when the pointer rests on a button or field that has one. Показывает подсказку, когда указатель задерживается на кнопке или поле, у которых она есть. Shows a warning before a script you choose runs. Показывает предупреждение перед запуском выбранного вами скрипта. + Runs the scripts in the Startup Scripts folder when VectorCraft starts and before each script from File › Scripts; not in Safe Mode. Запускает сценарии из папки Startup Scripts при запуске VectorCraft и перед каждым сценарием из меню Файл › Сценарии; не в безопасном режиме. Smooths the edges of artwork on the canvas. Сглаживает края графики на холсте. Select › Same › Fill Color, Stroke Color and Fill & Stroke match only the same tint of a global or spot swatch, not any tint of it. «Выделение › То же › Цвет заливки», «Цвет обводки» и «Заливка и обводка» находят только тот же оттенок глобального или плашечного образца, а не любой его оттенок. Shows the Home screen when no document is open; off, the window stays empty until you click Home. Показывает начальный экран, когда нет открытых документов; если выключено, окно остаётся пустым, пока вы не нажмёте «Домой». @@ -4921,6 +4922,7 @@ axis Both Оба Run Script Выполнить скрипт Stop Script Остановить скрипт Show External Script Warning Показывать предупреждение о внешних скриптах + Run Startup Scripts Запускать сценарии автозагрузки A Script Is Running Выполняется скрипт Script Alert Сообщение скрипта Script File Access Доступ скрипта к файлам diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index c26474cf93..90bedf9d78 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -3231,6 +3231,7 @@ digits Malayalam Malayalam Drawing tools show a crosshair pointer instead of their icon; Caps Lock does the same while it is on. Ritverktyg visar en hårkorspekare i stället för sin ikon; Caps Lock gör samma sak medan den är på. Shows a tip when the pointer rests on a button or field that has one. Visar ett tips när pekaren vilar på en knapp eller ett fält som har ett. Shows a warning before a script you choose runs. Visar en varning innan ett skript som du väljer körs. + Runs the scripts in the Startup Scripts folder when VectorCraft starts and before each script from File › Scripts; not in Safe Mode. Kör skripten i mappen Startup Scripts när VectorCraft startar och före varje skript från Fil › Skript; inte i felsäkert läge. Smooths the edges of artwork on the canvas. Jämnar ut kanterna på grafiken på arbetsytan. Select › Same › Fill Color, Stroke Color and Fill & Stroke match only the same tint of a global or spot swatch, not any tint of it. Markera › Samma › Fyllnadsfärg, Konturfärg och Fyllning och kontur hittar bara samma nyans av ett globalt färgprov eller en dekorfärg, inte vilken nyans som helst av det. Shows the Home screen when no document is open; off, the window stays empty until you click Home. Visar startskärmen när inget dokument är öppet; när det är av förblir fönstret tomt tills du klickar på Start. @@ -4783,6 +4784,7 @@ axis Both Båda Run Script Kör skript Stop Script Stoppa skript Show External Script Warning Visa varning för externa skript + Run Startup Scripts Kör startskript A Script Is Running Ett skript körs Script Alert Skriptmeddelande Script File Access Skriptets filåtkomst diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index 82186ebcdd..08940138fc 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -3076,6 +3076,7 @@ digits Malayalam Malayalam Drawing tools show a crosshair pointer instead of their icon; Caps Lock does the same while it is on. Çizim araçları simgeleri yerine artı işaretli bir imleç gösterir; Caps Lock açıkken aynısını yapar. Shows a tip when the pointer rests on a button or field that has one. İmleç ipucu olan bir düğme veya alan üzerinde durduğunda ipucunu gösterir. Shows a warning before a script you choose runs. Seçtiğiniz bir komut dosyası çalışmadan önce uyarı gösterir. + Runs the scripts in the Startup Scripts folder when VectorCraft starts and before each script from File › Scripts; not in Safe Mode. VectorCraft başladığında ve Dosya › Komut dosyaları menüsündeki her komut dosyasından önce Startup Scripts klasöründeki komut dosyalarını çalıştırır; Güvenli Mod'da çalıştırmaz. Smooths the edges of artwork on the canvas. Tuvaldeki resmin kenarlarını yumuşatır. Select › Same › Fill Color, Stroke Color and Fill & Stroke match only the same tint of a global or spot swatch, not any tint of it. Seçim › Aynı › Dolgu Rengi, Kontur Rengi ve Doldur ve Konturla yalnızca genel veya spot renk örneğinin aynı tonunu bulur, herhangi bir tonunu değil. Shows the Home screen when no document is open; off, the window stays empty until you click Home. Hiçbir belge açık değilken Ana Sayfa ekranını gösterir; kapalıyken siz Ana Sayfa'ya tıklayana kadar pencere boş kalır. @@ -4635,6 +4636,7 @@ axis Both Her İkisi Run Script Betiği Çalıştır Stop Script Betiği Durdur Show External Script Warning Harici Betik Uyarısını Göster + Run Startup Scripts Başlangıç Betiklerini Çalıştır A Script Is Running Bir Betik Çalışıyor Script Alert Betik Uyarısı Script File Access Betik Dosya Erişimi diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index de3329ef10..d3eff0fced 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -3352,6 +3352,7 @@ digits Malayalam Малаялам Drawing tools show a crosshair pointer instead of their icon; Caps Lock does the same while it is on. Інструменти малювання показують вказівник-перехрестя замість свого значка; Caps Lock робить те саме, поки він увімкнений. Shows a tip when the pointer rests on a button or field that has one. Показує підказку, коли вказівник зупиняється на кнопці або полі, що її мають. Shows a warning before a script you choose runs. Показує попередження перед запуском вибраного вами скрипту. + Runs the scripts in the Startup Scripts folder when VectorCraft starts and before each script from File › Scripts; not in Safe Mode. Запускає сценарії з папки Startup Scripts під час запуску VectorCraft і перед кожним сценарієм з меню Файл › Сценарії; не в безпечному режимі. Smooths the edges of artwork on the canvas. Згладжує краї графіки на полотні. Select › Same › Fill Color, Stroke Color and Fill & Stroke match only the same tint of a global or spot swatch, not any tint of it. «Виділення › Те саме › Колір заливки», «Колір обведення» та «Заливка та обведення» знаходять лише той самий відтінок глобального або плашкового зразка, а не будь-який його відтінок. Shows the Home screen when no document is open; off, the window stays empty until you click Home. Показує початковий екран, коли немає відкритих документів; якщо вимкнено, вікно лишається порожнім, доки ви не натиснете «Додому». @@ -4929,6 +4930,7 @@ axis Both Обидві Run Script Виконати скрипт Stop Script Зупинити скрипт Show External Script Warning Показувати попередження про зовнішні скрипти + Run Startup Scripts Запускати сценарії автозапуску A Script Is Running Виконується скрипт Script Alert Повідомлення скрипту Script File Access Доступ скрипту до файлів diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index 675143a8d6..749c0ff9de 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -3672,6 +3672,7 @@ mark-style Japanese Kiểu Nhật Drawing tools show a crosshair pointer instead of their icon; Caps Lock does the same while it is on. Các công cụ vẽ hiển thị con trỏ hình chữ thập thay cho biểu tượng của chúng; Caps Lock cũng làm vậy khi đang bật. Shows a tip when the pointer rests on a button or field that has one. Hiển thị mẹo khi con trỏ dừng trên một nút hoặc trường có mẹo. Shows a warning before a script you choose runs. Hiển thị cảnh báo trước khi một tập lệnh bạn chọn chạy. + Runs the scripts in the Startup Scripts folder when VectorCraft starts and before each script from File › Scripts; not in Safe Mode. Chạy các tập lệnh trong thư mục Startup Scripts khi VectorCraft khởi động và trước mỗi tập lệnh từ Tệp › Script; không chạy ở chế độ an toàn. Smooths the edges of artwork on the canvas. Làm mịn các cạnh của hình minh họa trên khung vẽ. Select › Same › Fill Color, Stroke Color and Fill & Stroke match only the same tint of a global or spot swatch, not any tint of it. Vùng chọn › Giống nhau › Màu tô, Màu nét và Tô & Nét chỉ khớp với cùng sắc độ của một mẫu màu toàn cục hoặc màu pha, không phải mọi sắc độ của nó. Shows the Home screen when no document is open; off, the window stays empty until you click Home. Hiển thị màn hình Trang chủ khi không có tài liệu nào mở; khi tắt, cửa sổ để trống cho đến khi bạn nhấp vào Trang chủ. @@ -5407,6 +5408,7 @@ theme Appearance Giao diện Run Script Chạy tập lệnh Stop Script Dừng tập lệnh Show External Script Warning Hiện cảnh báo tập lệnh bên ngoài + Run Startup Scripts Chạy tập lệnh khởi động A Script Is Running Một tập lệnh đang chạy Script Alert Thông báo của tập lệnh Script File Access Quyền truy cập tệp của tập lệnh diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index 57f6a4403b..9658c0d9e6 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -3201,6 +3201,7 @@ digits Malayalam 马拉雅拉姆数字 Drawing tools show a crosshair pointer instead of their icon; Caps Lock does the same while it is on. 绘图工具显示十字指针而不是工具图标;Caps Lock 打开时效果相同。 Shows a tip when the pointer rests on a button or field that has one. 指针停在带有提示的按钮或字段上时显示提示。 Shows a warning before a script you choose runs. 在你选择的脚本运行前显示警告。 + Runs the scripts in the Startup Scripts folder when VectorCraft starts and before each script from File › Scripts; not in Safe Mode. 在 VectorCraft 启动时以及运行“文件 › 脚本”中的每个脚本前,运行 Startup Scripts 文件夹中的脚本;安全模式下不运行。 Smooths the edges of artwork on the canvas. 使画布上图稿的边缘平滑。 Select › Same › Fill Color, Stroke Color and Fill & Stroke match only the same tint of a global or spot swatch, not any tint of it. 选择 › 相同 › 填色、描边颜色和填色和描边只匹配全局色板或专色色板的相同色调,而不是其任意色调。 Shows the Home screen when no document is open; off, the window stays empty until you click Home. 没有打开文档时显示主页屏幕;关闭时,窗口保持空白,直到你点击主页。 @@ -5436,6 +5437,7 @@ imageTrace Outline 轮廓 Run Script 运行脚本 Stop Script 停止脚本 Show External Script Warning 显示外部脚本警告 + Run Startup Scripts 运行启动脚本 A Script Is Running 脚本正在运行 Script Alert 脚本提示 Script File Access 脚本文件访问 diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index 9834c17ea6..a2410f6810 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -2782,6 +2782,7 @@ file-filter Templates 範本 Run Script 執行指令碼 Stop Script 停止指令碼 Show External Script Warning 顯示外部指令碼警告 + Run Startup Scripts 執行啟動指令碼 A Script Is Running 指令碼正在執行 Script Alert 指令碼提示 Script File Access 指令碼檔案存取 @@ -4650,6 +4651,7 @@ digits Malayalam 馬來亞拉姆數字 Drawing tools show a crosshair pointer instead of their icon; Caps Lock does the same while it is on. 繪圖工具顯示十字指標而不是工具圖示;Caps Lock 開啟時效果相同。 Shows a tip when the pointer rests on a button or field that has one. 指標停在有提示的按鈕或欄位上時顯示提示。 Shows a warning before a script you choose runs. 在你選擇的指令碼執行前顯示警告。 + Runs the scripts in the Startup Scripts folder when VectorCraft starts and before each script from File › Scripts; not in Safe Mode. 在 VectorCraft 啟動時以及執行「檔案 › 指令碼」中的每個指令碼前,執行 Startup Scripts 資料夾中的指令碼;安全模式下不執行。 Smooths the edges of artwork on the canvas. 使畫布上圖稿的邊緣平滑。 Select › Same › Fill Color, Stroke Color and Fill & Stroke match only the same tint of a global or spot swatch, not any tint of it. 選取 › 相同 › 填色顏色、筆畫顏色和填色與筆畫只符合全域色票或特別色色票的相同色調,而不是其任意色調。 Shows the Home screen when no document is open; off, the window stays empty until you click Home. 沒有開啟文件時顯示首頁畫面;關閉時,視窗保持空白,直到你按下首頁。 diff --git a/crates/ui-egui/src/prefs_dialog/descriptions.rs b/crates/ui-egui/src/prefs_dialog/descriptions.rs index ec8aea7063..1faa11f995 100644 --- a/crates/ui-egui/src/prefs_dialog/descriptions.rs +++ b/crates/ui-egui/src/prefs_dialog/descriptions.rs @@ -18,6 +18,10 @@ pub(crate) const DESCRIPTIONS: &[(&str, &str)] = &[ ("showToolTips", "Shows a tip when the pointer rests on a button or field that has one."), ("showToolCards", "Shows a card with what a toolbar tool does and what its keys do instead of its tip; it needs Show Tool Tips."), ("showExternalScriptWarning", "Shows a warning before a script you choose runs."), + ( + "runStartupScripts", + "Runs the scripts in the Startup Scripts folder when VectorCraft starts and before each script from File › Scripts; not in Safe Mode.", + ), ("antiAliasedArtwork", "Smooths the edges of artwork on the canvas."), ( "selectSameTintPercent", diff --git a/crates/ui-egui/src/script_runs.rs b/crates/ui-egui/src/script_runs.rs index 7bc52f35b1..ab125bf44f 100644 --- a/crates/ui-egui/src/script_runs.rs +++ b/crates/ui-egui/src/script_runs.rs @@ -3,7 +3,7 @@ //! shows it with a Stop button; a run that has added a great deal, or that opened a dialog with //! `alert`, `confirm`, `prompt` or a `File` or `Folder` file dialog, waits for the person's answer. -use serde_json::json; +use serde_json::{Value, json}; use crate::VectorcraftApp; use crate::dialogs::script_run; @@ -12,6 +12,10 @@ use crate::state::Dialog; /// Advances the running script by one slice, or asks what its growth needs asked. pub fn poll(app: &mut VectorcraftApp) { script_run::drain(app); + // Each run `script.startup.run` queued that could not start. + for (name, error) in app.session.take_startup_failures() { + app.status(format!("{name}: {error}")); + } if !app.session.script_running() { return; } @@ -77,6 +81,26 @@ fn ask(app: &mut VectorcraftApp) -> bool { false } +/// Runs the script of `params` (`script.run`'s) that the person chose from File › Scripts, after +/// the startup scripts when General › Run Startup Scripts is on (`script.startup.run`). +pub(crate) fn run_chosen(app: &mut VectorcraftApp, params: Value) -> Result { + if app.session.startup_skip().is_some() { + return app.run("script.run", params); + } + app.run("script.startup.run", json!({"reason": "menu", "then": params})) +} + +/// When the app has started, out of Safe Mode: the startup scripts run when General › Run Startup +/// Scripts is on (`script.startup.run`). A failure to start them shows in the status bar. +pub fn run_at_launch(app: &mut VectorcraftApp) { + if app.session.startup_skip().is_some() { + return; + } + if let Err(e) = app.run("script.startup.run", json!({"reason": "launch"})) { + app.status(e); + } +} + /// Shows why a run ended without its changes. A stopped run that wrote no file says only that it /// was stopped; any other failure shows its error, which names the files left written. pub(crate) fn failed(app: &mut VectorcraftApp, error: String) { diff --git a/crates/ui-egui/src/scripts_menu.rs b/crates/ui-egui/src/scripts_menu.rs index 1afaf11d34..3c7a19a49f 100644 --- a/crates/ui-egui/src/scripts_menu.rs +++ b/crates/ui-egui/src/scripts_menu.rs @@ -13,7 +13,8 @@ //! //! `ui.runInstalledScript {path}` runs a listed script (`script.run`) without the warning Other //! Script… shows: the file was put in the folder to be run from the menu. The path is one a -//! listing gave; a file that is no longer a plain script under the folder is not run. +//! listing gave; a file that is no longer a plain script under the folder is not run. With General › +//! Run Startup Scripts on, the startup scripts run first (`script.startup.run`). use std::path::Path; use std::sync::mpsc::{Receiver, TryRecvError}; @@ -341,7 +342,12 @@ pub fn readable(p: &Value) -> bool { /// folder is read again. pub fn run(app: &mut VectorcraftApp, p: &Value) -> Result { let path = p.get("path").and_then(Value::as_str).ok_or("missing `path`")?; - app.run("script.run", json!({ "path": path, "installed": true })).inspect_err(|e| { + // With startup scripts to run first, a script no longer in the folder is found before they run. + let listed = match app.session.startup_skip() { + Some(_) => Ok(()), + None => app.session.installed_script(path).map(drop).map_err(|e| e.to_string()), + }; + listed.and_then(|()| crate::script_runs::run_chosen(app, json!({ "path": path, "installed": true }))).inspect_err(|e| { if e == NOT_LISTED { let ctx = app.ui_ctx.clone(); refresh(app, ctx.as_ref()); diff --git a/crates/ui-egui/src/tests/scripts_menu.rs b/crates/ui-egui/src/tests/scripts_menu.rs index 02c077e9af..f7fb97f11d 100644 --- a/crates/ui-egui/src/tests/scripts_menu.rs +++ b/crates/ui-egui/src/tests/scripts_menu.rs @@ -536,6 +536,70 @@ fn a_slow_first_read_says_so_until_its_listing_comes() { let _ = std::fs::remove_dir_all(dir); } +/// The names of the runs the Script Console started, in order. +fn started(app: &VectorcraftApp) -> Vec { + let lines = app.session.script_console().to_json(); + lines["lines"].as_array().unwrap().iter().filter(|l| l["kind"] == "start").map(|l| l["name"].as_str().unwrap().to_string()).collect() +} + +/// `dir`'s `Startup Scripts` folder, attached to `app`, holding `a.jsx` that draws one rectangle. +fn startup_folder(app: &mut VectorcraftApp, dir: &std::path::Path) { + let startup = dir.join("Startup Scripts"); + std::fs::create_dir_all(&startup).unwrap(); + std::fs::write(startup.join("a.jsx"), "vc.run('shape.rectangle', {x:40,y:0,width:10,height:10});").unwrap(); + app.session.attach_startup_scripts_dir(startup); +} + +#[test] +fn with_run_startup_scripts_on_a_listed_script_runs_after_the_startup_scripts() { + let dir = folder("startup"); + let mut app = app(&dir); + startup_folder(&mut app, &dir); + let draw = write(&dir, "Draw Two.jsx", DRAW); + read(&app); + // Off by default: the listed script runs alone. + menus::run_ui_command(&mut app, scripts_menu::COMMAND, &json!({ "path": draw })).unwrap().unwrap(); + finish(&mut app); + assert_eq!(started(&app), ["Draw Two.jsx"]); + assert_eq!(objects(&app), 2); + app.run("prefs.set", json!({"key": "runStartupScripts", "value": true})).unwrap(); + let undo = app.session.doc().unwrap().history.undo.len(); + menus::run_ui_command(&mut app, scripts_menu::COMMAND, &json!({ "path": draw })).unwrap().unwrap(); + assert!(app.session.script_running()); + finish(&mut app); + assert_eq!(started(&app), ["Draw Two.jsx", "a.jsx", "Draw Two.jsx"], "the startup script runs first"); + assert_eq!(objects(&app), 5); + assert_eq!(app.session.doc().unwrap().history.undo.len(), undo + 2, "an undo step for each run"); + assert_eq!(app.ui.status, "Ran Draw Two.jsx"); + // A script that left the folder runs neither itself nor the startup scripts. + std::fs::remove_file(&draw).unwrap(); + let e = menus::run_ui_command(&mut app, scripts_menu::COMMAND, &json!({ "path": draw })).unwrap().unwrap_err(); + assert_eq!(e, "the script is no longer in the Scripts folder"); + assert!(!app.session.script_running()); + assert_eq!(started(&app).len(), 3); + scripts_menu::wait(); + let _ = std::fs::remove_dir_all(dir); +} + +#[test] +fn with_run_startup_scripts_on_other_script_and_the_launch_run_the_startup_scripts() { + let dir = folder("startup-other"); + let mut app = app(&dir); + startup_folder(&mut app, &dir); + app.session.prefs.show_external_script_warning = false; + script_runs::run_at_launch(&mut app); + assert!(!app.session.script_running(), "off by default, nothing runs at launch"); + app.run("prefs.set", json!({"key": "runStartupScripts", "value": true})).unwrap(); + script_runs::run_at_launch(&mut app); + finish(&mut app); + assert_eq!(started(&app), ["a.jsx"]); + menus::run_ui_command(&mut app, "ui.runScript", &json!({ "source": DRAW, "name": "chosen" })).unwrap().unwrap(); + finish(&mut app); + assert_eq!(started(&app), ["a.jsx", "a.jsx", "chosen"]); + assert_eq!(objects(&app), 4); + let _ = std::fs::remove_dir_all(dir); +} + #[test] fn a_first_read_that_ends_without_a_listing_says_the_folder_cannot_be_read_and_the_next_read_tries_again() { let dir = folder("lost"); diff --git a/crates/ui-egui/tests/safe_mode.rs b/crates/ui-egui/tests/safe_mode.rs index 246352e469..57a13e8321 100644 --- a/crates/ui-egui/tests/safe_mode.rs +++ b/crates/ui-egui/tests/safe_mode.rs @@ -137,6 +137,42 @@ fn disable_and_continue_loads_every_plug_in_but_the_one_that_was_loading() { let _ = std::fs::remove_dir_all(&dir); } +#[test] +fn startup_scripts_wait_for_the_choice_and_disable_and_continue_leaves_out_the_one_that_was_running() { + let _f = fresh(); + let dir = tmp_dir("startup"); + let scripts = dir.join("Startup Scripts"); + std::fs::create_dir_all(&scripts).unwrap(); + let a = scripts.join("a.jsx"); + std::fs::write(&a, "vc.log('a');").unwrap(); + std::fs::write(scripts.join("b.jsx"), "vc.log('b');").unwrap(); + let launch_dir = dir.join("Launch"); + std::fs::create_dir_all(&launch_dir).unwrap(); + let item = json!({"format": "vectorcraft-launch", "version": 1, "item": {"file": a.display().to_string(), "name": "a.jsx"}}); + std::fs::write(launch_dir.join("launch-1-dead.json"), item.to_string()).unwrap(); + let stopped = ui::begin_launch(Some(&launch_dir), false); + let mut session = Session::new(); + session.attach_startup_scripts_dir(scripts); + session.prefs.run_startup_scripts = true; + let mut app = VectorcraftApp::new(session, Services::default()); + ui::after_start(&mut app, stopped); + assert_eq!(kind(&app), Some(ui::STOPPED)); + vectorcraft_ui_egui::script_runs::run_at_launch(&mut app); + assert!(!app.session.script_running(), "nothing runs while Safe Mode waits for the choice"); + dialogs::confirm(&mut app).unwrap(); + for _ in 0..10_000 { + if !app.session.script_running() { + break; + } + vectorcraft_ui_egui::script_runs::poll(&mut app); + } + let lines = app.session.script_console().to_json(); + let started: Vec<&str> = lines["lines"].as_array().unwrap().iter().filter(|l| l["kind"] == "start").filter_map(|l| l["name"].as_str()).collect(); + assert_eq!(started, ["b.jsx"], "the startup scripts run once Safe Mode ends, without the disabled one"); + done(&launch_dir); + let _ = std::fs::remove_dir_all(&dir); +} + #[test] fn start_normally_loads_everything_and_start_in_safe_mode_loads_nothing() { let _f = fresh(); diff --git a/docs/mcp.md b/docs/mcp.md index 5032690fc6..6014952152 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -3133,6 +3133,50 @@ leaves out the listed scripts outside the read roots. vectorcraft-cli run --cmd script.listInstalled --params '{}' ``` +### Startup scripts + +With Preferences › General › Run Startup Scripts on (`runStartupScripts`, off by default), the `.jsx` files of the +`Startup Scripts` folder next to the preferences run when VectorCraft starts, and again before each script chosen from +File › Scripts, whether a listed script or Other Script…. The folder is `~/Library/Application +Support/VectorCraft/Startup Scripts` on macOS, `%APPDATA%\VectorCraft\Startup Scripts` on Windows, and +`$XDG_CONFIG_HOME/vectorcraft/Startup Scripts` or `~/.config/vectorcraft/Startup Scripts` on Linux and BSD. +VectorCraft does not make the folder. The scripting guide +https://web.archive.org/web/20210515232518/https://www.adobe.com/content/dam/acom/en/devnet/illustrator/pdf/Illustrator_Scripting_Guide_cc.pdf +(page 11) describes startup scripts as `.jsx` files that run when the application starts and each time a script is +run. + +The rest of this section is VectorCraft's own rules: + +- Only the folder's own `.jsx` files run, never its subfolders. Links, names that start with a dot, files Windows marks + hidden or system, names longer than 255 bytes and other file types are left out. A listing stops at 2,048 folder + entries, 512 scripts or 250 ms. A folder that is missing runs nothing. +- The scripts run one at a time, sorted by name without regard to case, then by name. Each runs as `script.run` runs a + file, with the same limits, and each that changes a document adds its own Run Script undo step. The chosen script + runs after the last of them. +- A startup script that cannot be read, is larger than 8 MiB, throws, runs out of instructions or is stopped is named + in the Script Console and the status bar, and the next one runs. The app opens and the chosen script runs either way. +- In Safe Mode nothing in the folder runs. After a launch that stopped, the startup scripts run once the person + chooses Disable and Continue or Start Normally. While a startup script runs, the launch marker names it, so a launch + that stops during one offers to disable that script. A disabled startup script does not run, and the reply names it + in `disabled`. +- Running the startup scripts is itself a `script.*` command, which a script cannot run, so a startup script cannot + start another round of them. `script.run` called from automation runs alone. +- The web build has no Startup Scripts folder, and neither has a run with `VECTORCRAFT_NO_PREFS` set. + +`script.startup.run {reason: launch|menu, then?, maxFuel?}` runs the folder now. `then` holds `script.run`'s +parameters for a script that runs after the startup scripts; `maxFuel` limits each startup script's instructions +(from 1 to 100,000,000,000, default 1,000,000,000). It returns `{reason, skipped: true, why}` with `why` set to `off`, +`safeMode` or `noFolder` when nothing runs, and otherwise `{reason, skipped: false, ran, failed: [{name, error}], +disabled, truncated, unreadable}`, with `then` holding `script.run`'s reply. In the app the runs are queued and the +reply is `{reason, skipped: false, running, queued, failed, disabled, truncated, unreadable}`, with `failed` naming +the runs that could not start before the first one did; each run then reports as a `script.run` in the app does, and +a later run that cannot start, the chosen script included, is named in the status bar. Under `--automation-read-root` it reads the folder only when the folder lies inside a +read root. + +```sh +vectorcraft-cli run --cmd script.startup.run --params '{"reason": "launch"}' +``` + ## Transparency and opacity masks Transparency and opacity-mask commands take `ids` (or `id`), so they need no selection. Opacity is a percentage diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index f8a3dc84a0..2c76f33375 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1042,6 +1042,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - Scripts: `File` and `Folder` write ([File object](https://extendscript.docsforadobe.dev/file-system-access/file-object/), [Folder object](https://extendscript.docsforadobe.dev/file-system-access/folder-object/)): `open('w')`, `open('e')` and `open('a')` with `write` and `writeln` by `lineFeed`, `copy`, `remove` (a folder only when empty), `rename`, `folder.create()`, the `length` and `readonly` setters, and `File.openDialog`, `File.saveDialog`, `Folder.selectDialog`, `openDlg`, `saveDlg` and `selectDlg`, with a `filter` of file types or a filter function and `multiSelect`. VectorCraft's own rules: a script writes only in `Folder.temp` (one for the run, deleted when it ends), its own `Folder.userData` next to the settings, and what a person allowed it in a file dialog, once or always; Always keeps the grant for that script file with that text by its SHA-256 and for the sources the run evaluated (`$.evalFile`, `eval`, `Function`), so a run that evaluates other code, or whose named engine holds other code, loses it first; `script.grants` lists the grants and `script.grants.revoke` removes them; the settings folder is kept out of every grant; the commands a script runs with `vc.run` read and write only in the same places and the open documents' own files; a run with nobody to ask gets `null` from the dialogs; a file is written at close or when the run ends, 8 MiB a file and 32 MiB a run, and named in `written`, also after a run that failed. `crates/engine/src/tests/script_io.rs`. - Scripts: `#strict on` (and `//@strict on`) runs the script with the checks the [`$` object](https://extendscript.docsforadobe.dev/extendscript-tools-features/dollar-object/) help page gives for `$.strict`: an assignment to a read-only property throws a `TypeError`, and so does a new property on an object that takes none. VectorCraft's own rules: a getter-only property counts as read-only, the objects that take no new properties are the non-extensible ones (`Object.preventExtensions`, `seal`, `freeze`, and the frozen `vc` and `$` objects), the last `#strict` line of the script and its includes sets the whole run, a file `$.evalFile` runs keeps its own line's checks for its code, and the rest of ES5 strict mode stays with `'use strict'`. Without the line, runs are unchanged. `crates/engine/src/tests/script_include.rs` (`strict_on_*`, `strict_mode_in_eval_file_is_scoped`), `crates/js/src/interp_tests.rs` (`strict_writes_are_separate_from_es5_strict`). - Scripts folder: File › Scripts lists the `.js` and `.jsx` files of the `Scripts` folder next to the preferences, each named after its file without the extension, with each subfolder as a submenu, above Check Script… and Other Script… (https://helpx.adobe.com/illustrator/desktop/automate-visualize-data/automate-actions/install-and-run-scripts.html). VectorCraft's own rules: the folder is read again when the window becomes active and when the File menu opens (in the macOS menu bar, when any of its menus opens, and the new listing shows the next time the menu opens), links are not followed, and one read stops at 2,048 entries, 512 scripts, 128 subfolders, 4 levels or 250 ms. `script.listInstalled` returns the listing. `crates/engine/src/tests/script_folder.rs`, `crates/ui-egui/src/tests/scripts_menu.rs`. + - Startup scripts: with Preferences › General › Run Startup Scripts on, the `.jsx` files of the `Startup Scripts` folder next to the preferences run when VectorCraft starts and before each script chosen from File › Scripts ([the scripting guide](https://web.archive.org/web/20210515232518/https://www.adobe.com/content/dam/acom/en/devnet/illustrator/pdf/Illustrator_Scripting_Guide_cc.pdf), page 11). VectorCraft's own rules: the preference is off by default; only the folder's own `.jsx` files run, sorted by name without regard to case, each with the limits of any script and its own undo step; one that fails is named in the Script Console and the next one runs, then the chosen script; nothing runs in Safe Mode, the launch marker names the running startup script so a launch that stops there offers to disable it, and a startup script cannot start another round. `script.startup.run` runs the folder. `crates/engine/tests/script_startup.rs`, `crates/ui-egui/src/tests/scripts_menu.rs`, `crates/ui-egui/tests/safe_mode.rs`. - Messages over the window: `app.toast {message, level?, seconds?}` shows a message at the window's bottom right that does not stop work and closes after its time (4 seconds by default) or when clicked; at most 5 show at once, the newest lowest. Scripts raise one through `vc.run`, MCP clients through the command, and an action records it as a step. The limits are VectorCraft's own values. Tests: `cmd::toast::tests` in `vectorcraft-engine`, `toasts::tests` in `vectorcraft-ui-egui`. - Open Recent Files under `--automation-read-root`: the control channel's `ui.menu.list` and `file.recentFiles` leave out the recent files outside the read roots, the other rows keep their ids, and `file.openRecentN` for one outside them answers `no such recent file`, as an empty slot does. `crates/ui-egui/src/tests/automation.rs`. - Saves, Export for Screens and Package under `--automation-read-root`: a save without a path leaves the document's own file out of its reply, and a save without a path known leaves out the suggested folder, when they are outside the read roots; Export for Screens into an export preset's folder outside them lists its files relative to that folder and names that folder by its name in an error, and the export settings and saved presets leave out a folder outside them when read or exported; Package's report and warnings, and Document Info's linked images, name a file outside them by its file name. A path the client gives stays in the reply. `crates/engine/src/tests/save.rs`, `crates/engine/src/cmd/fileio/tests_screens.rs`, `crates/engine/src/tests/package.rs`, `crates/ui-egui/src/tests/automation.rs`. From ec1888430876428c15c42a224ed4560f1dd09197 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 20:24:16 -0800 Subject: [PATCH 039/151] Quick Pen: a click on a path edited during the press does nothing When another command edits the path while a click on one of its anchors is down, the release no longer selects an anchor or goes on drawing from the open end the press found. Before, the click used the anchor index and the end it had stored before the edit. --- crates/engine/src/tests/quickpen.rs | 18 ++++++++++++++++++ crates/tools/src/quickpen.rs | 6 +++++- crates/tools/src/quickpen/edit.rs | 14 +++++++++----- 3 files changed, 32 insertions(+), 6 deletions(-) diff --git a/crates/engine/src/tests/quickpen.rs b/crates/engine/src/tests/quickpen.rs index d3746d3c8e..412406c80a 100644 --- a/crates/engine/src/tests/quickpen.rs +++ b/crates/engine/src/tests/quickpen.rs @@ -684,6 +684,24 @@ fn an_edit_during_an_edit_press_stops_the_move() { } } +/// When another command edits the path while a click is down, the click neither selects the +/// anchor nor goes on drawing from the open end it found. +#[test] +fn an_edit_during_an_edit_click_does_nothing() { + let mut s = session(); + let id = selected_quick_pen_path(&mut s, (100.0, 100.0), json!([{"x": 200, "y": 100}, {"x": 300, "y": 100}])); + let v = view(); + for (x, moved_y) in [(200.0, 90.0), (300.0, 80.0)] { + s.pointer(&PointerEvent::new(PointerKind::Down, x, 100.0), v).unwrap(); + s.execute("path.moveAnchor", &json!({"id": id.0, "anchor": 0, "x": 100, "y": moved_y})).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Up, x, 100.0), v).unwrap(); + assert!(s.doc().unwrap().selection.partial(id).is_none(), "no anchor selected after a click at x = {x}"); + } + // The open end was not taken up, so the next click starts a new path. + click(&mut s, 400.0, 200.0); + assert_eq!(paths(&s).len(), 2); +} + /// A click on an anchor selects it alone, Shift-click adds another, and Delete (`edit.clear`, the /// context menu's Delete) then removes both. #[test] diff --git a/crates/tools/src/quickpen.rs b/crates/tools/src/quickpen.rs index f76cf806bf..c3188250fb 100644 --- a/crates/tools/src/quickpen.rs +++ b/crates/tools/src/quickpen.rs @@ -500,7 +500,8 @@ impl QuickPenTool { /// go past the drag distance after shorter drag events, moves what it holds to `p` and ends /// its undo step. A click on an end of an open path goes on drawing from it, a click on another /// anchor selects it alone (with Shift, adds it to the selected anchors or takes it out), and a - /// click on a segment starts a new path there. + /// click on a segment starts a new path there. A click whose path another command edited while + /// the press was down does nothing. fn release_edit(&mut self, cx: &ToolContext, mut e: Edit, p: Point) -> Vec { if e.began || p.distance(e.start) >= cx.tol(DRAG_PX) { let mut out = e.drag(cx, p); @@ -510,6 +511,9 @@ impl QuickPenTool { } return out; } + if !e.unchanged(cx) { + return vec![]; + } match e.grab { Grab::Anchor { id, si, ai, .. } if e.shift => { // `select.anchors` toggles from every anchor of a path selected whole on its own, diff --git a/crates/tools/src/quickpen/edit.rs b/crates/tools/src/quickpen/edit.rs index 3e1e0509a7..a7d5f6de55 100644 --- a/crates/tools/src/quickpen/edit.rs +++ b/crates/tools/src/quickpen/edit.rs @@ -93,6 +93,14 @@ impl Edit { Self { grab, start, shift, began: false, pressed, snap: None, guides: vec![] } } + /// Whether the grabbed path is as the document had it when the press went down. + pub(super) fn unchanged(&self, cx: &ToolContext) -> bool { + match (cx.doc.node(self.grab.id()), self.pressed.as_ref()) { + (Some(now), Some(then)) => same_node(now, then), + _ => false, + } + } + /// Moves what the press holds by the drag to `p`. The first move selects the anchor, or the /// segment, unless it is already selected, and begins the undo step; a drag that starts on /// one of several selected anchors moves them all. When the grabbed path changed after the @@ -101,11 +109,7 @@ impl Edit { let mut out = vec![]; if !self.began { let id = self.grab.id(); - let unchanged = match (cx.doc.node(id), self.pressed.as_ref()) { - (Some(now), Some(then)) => same_node(now, then), - _ => false, - }; - if !unchanged { + if !self.unchanged(cx) { return out; } let Some(picked) = self.grab.anchors(cx) else { return out }; From 059628a14cfc685fda8b65cc451b9276499bf228 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 20:47:12 -0800 Subject: [PATCH 040/151] Quick Pen: a drag back to its start records no undo step A drag on an anchor or a segment that is let go where it started now moves nothing and adds no undo step. Before, it recorded a Move step that changed nothing. --- crates/engine/src/tests/quickpen.rs | 14 ++++++++++++++ crates/tools/src/quickpen.rs | 5 +++-- crates/tools/src/quickpen/edit.rs | 5 ++++- 3 files changed, 21 insertions(+), 3 deletions(-) diff --git a/crates/engine/src/tests/quickpen.rs b/crates/engine/src/tests/quickpen.rs index 412406c80a..b1142eff1f 100644 --- a/crates/engine/src/tests/quickpen.rs +++ b/crates/engine/src/tests/quickpen.rs @@ -664,6 +664,20 @@ fn a_release_past_the_drag_distance_moves_the_anchor() { assert_eq!(paths(&s).len(), 1, "no new path"); } +/// A drag on an anchor or a segment that comes back to where it started moves nothing and records +/// no undo step. +#[test] +fn a_drag_back_to_its_start_records_no_undo_step() { + let mut s = session(); + selected_quick_pen_path(&mut s, (100.0, 100.0), json!([{"x": 200, "y": 100}, {"x": 300, "y": 100}])); + let undo = undo_steps(&s); + for at in [(200.0, 100.0), (250.0, 100.0)] { + press(&mut s, &[at, (at.0, at.1 + 50.0), at]); + assert_eq!(points(&s), [pt(100.0, 100.0), pt(200.0, 100.0), pt(300.0, 100.0)], "press at {at:?}"); + assert_eq!(undo_steps(&s), undo, "press at {at:?}"); + } +} + /// When another command edits the path while the press is down, neither a drag nor a release past /// the drag distance moves the anchor the press found. #[test] diff --git a/crates/tools/src/quickpen.rs b/crates/tools/src/quickpen.rs index c3188250fb..106f320e49 100644 --- a/crates/tools/src/quickpen.rs +++ b/crates/tools/src/quickpen.rs @@ -505,9 +505,10 @@ impl QuickPenTool { fn release_edit(&mut self, cx: &ToolContext, mut e: Edit, p: Point) -> Vec { if e.began || p.distance(e.start) >= cx.tol(DRAG_PX) { let mut out = e.drag(cx, p); - // A drag that could not begin (its path changed under the press) has no step to end. + // A drag that could not begin (its path changed under the press) has no step to end, + // and one that came back to where it started records none. if e.began { - out.push(Action::Commit); + out.push(if e.moved { Action::Commit } else { Action::Cancel }); } return out; } diff --git a/crates/tools/src/quickpen/edit.rs b/crates/tools/src/quickpen/edit.rs index a7d5f6de55..be23386268 100644 --- a/crates/tools/src/quickpen/edit.rs +++ b/crates/tools/src/quickpen/edit.rs @@ -81,6 +81,8 @@ pub(super) struct Edit { pub(super) shift: bool, /// Whether the press has dragged far enough to move what it holds (an undo step began). pub(super) began: bool, + /// Whether the last drag left what the press holds away from where it started. + pub(super) moved: bool, /// The grabbed path as the document had it when the press went down. pressed: Option>, snap: Option, @@ -90,7 +92,7 @@ pub(super) struct Edit { impl Edit { pub(super) fn new(cx: &ToolContext, grab: Grab, start: Point, shift: bool) -> Self { let pressed = shared_node(cx.doc, grab.id()).cloned(); - Self { grab, start, shift, began: false, pressed, snap: None, guides: vec![] } + Self { grab, start, shift, began: false, moved: false, pressed, snap: None, guides: vec![] } } /// Whether the grabbed path is as the document had it when the press went down. @@ -154,6 +156,7 @@ impl Edit { if !d.x.is_finite() || !d.y.is_finite() { return out; } + self.moved = d.x != 0.0 || d.y != 0.0; out.push(Action::Preview("path.moveAnchors".into(), json!({"dx": d.x, "dy": d.y, "interpolate": true}))); out } From 1410f7500c203b280308dc89606351634dd72d18 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 21:23:36 -0800 Subject: [PATCH 041/151] Quick Pen: an edit by another command during a drag stays When another command edits the document or the selection during a drag on an anchor or a segment, the drag now previews no more and its undo step keeps that edit with the move as last shown, also when Escape ends the drag. Before, the next drag event previewed from the document as it was before the edit, so the edit was lost. --- crates/engine/src/tests/quickpen.rs | 26 +++++++++++++++++++++++ crates/tools/src/quickpen.rs | 24 +++++++++++++-------- crates/tools/src/quickpen/edit.rs | 33 +++++++++++++++++++++++------ 3 files changed, 68 insertions(+), 15 deletions(-) diff --git a/crates/engine/src/tests/quickpen.rs b/crates/engine/src/tests/quickpen.rs index b1142eff1f..39cc07a530 100644 --- a/crates/engine/src/tests/quickpen.rs +++ b/crates/engine/src/tests/quickpen.rs @@ -698,6 +698,32 @@ fn an_edit_during_an_edit_press_stops_the_move() { } } +/// An edit made by another command during an anchor drag stays: the rest of the drag and the +/// release move nothing more, and one undo step holds the move as last shown with the edit. +#[test] +fn an_edit_during_an_anchor_drag_stays() { + let mut s = session(); + let id = selected_quick_pen_path(&mut s, (100.0, 100.0), json!([{"x": 200, "y": 100}, {"x": 300, "y": 100}])); + let undo = undo_steps(&s); + let v = view(); + s.pointer(&PointerEvent::new(PointerKind::Down, 200.0, 100.0), v).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Drag, 200.0, 150.0), v).unwrap(); + s.execute("path.moveAnchor", &json!({"id": id.0, "anchor": 0, "x": 90, "y": 90})).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Drag, 200.0, 200.0), v).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Up, 200.0, 210.0), v).unwrap(); + assert_eq!(points(&s), [pt(90.0, 90.0), pt(200.0, 150.0), pt(300.0, 100.0)], "the edit and the move as last shown"); + assert_eq!(undo_steps(&s), undo + 1); + assert!(!s.in_interaction(), "the step is committed"); + // Escape after such an edit keeps it too. + s.pointer(&PointerEvent::new(PointerKind::Down, 300.0, 100.0), v).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Drag, 300.0, 150.0), v).unwrap(); + s.execute("path.moveAnchor", &json!({"id": id.0, "anchor": 0, "x": 80, "y": 80})).unwrap(); + key(&mut s, ToolKey::Escape); + s.pointer(&PointerEvent::new(PointerKind::Up, 300.0, 200.0), v).unwrap(); + assert_eq!(points(&s), [pt(80.0, 80.0), pt(200.0, 150.0), pt(300.0, 150.0)]); + assert!(!s.in_interaction(), "the step is committed"); +} + /// When another command edits the path while a click is down, the click neither selects the /// anchor nor goes on drawing from the open end it found. #[test] diff --git a/crates/tools/src/quickpen.rs b/crates/tools/src/quickpen.rs index 106f320e49..bdb80c2a5b 100644 --- a/crates/tools/src/quickpen.rs +++ b/crates/tools/src/quickpen.rs @@ -484,15 +484,14 @@ impl QuickPenTool { } /// Ends the path being drawn; a press that added a piece, or moved part of a path, is taken - /// back. - fn end(&mut self) -> Vec { + /// back. A move that another command's edit interrupted is kept with that edit. + fn end(&mut self, cx: &ToolContext) -> Vec { self.drawing = None; self.snap.clear(); - let moved = self.edit.take().is_some_and(|e| e.began); + let moved = self.edit.take().filter(|e| e.began).map(|mut e| if e.open(cx) { Action::Cancel } else { Action::Commit }); match self.press.take() { Some(pr) if pr.begun => vec![Action::Cancel], - _ if moved => vec![Action::Cancel], - _ => vec![], + _ => moved.into_iter().collect(), } } @@ -505,10 +504,11 @@ impl QuickPenTool { fn release_edit(&mut self, cx: &ToolContext, mut e: Edit, p: Point) -> Vec { if e.began || p.distance(e.start) >= cx.tol(DRAG_PX) { let mut out = e.drag(cx, p); - // A drag that could not begin (its path changed under the press) has no step to end, - // and one that came back to where it started records none. + // A drag that could not begin (its path changed under the press) has no step to end. + // One that came back to where it started records none, unless another command's + // edit during the drag is in the step. if e.began { - out.push(if e.moved { Action::Commit } else { Action::Cancel }); + out.push(if e.moved || e.interrupted { Action::Commit } else { Action::Cancel }); } return out; } @@ -622,6 +622,12 @@ impl Tool for QuickPenTool { } fn notify(&mut self, cx: &ToolContext, what: &str) { + if what == edit::MOVED { + if let Some(e) = self.edit.as_mut() { + e.revision = Some(cx.revision); + } + return; + } let Some(dr) = self.drawing.as_mut() else { return }; if what == "created" && let [id] = cx.selection.objects.as_slice() @@ -686,7 +692,7 @@ impl Tool for QuickPenTool { fn key(&mut self, cx: &ToolContext, key: ToolKey, _mods: Mods) -> Vec { match key { - ToolKey::Escape | ToolKey::Enter => self.end(), + ToolKey::Escape | ToolKey::Enter => self.end(cx), ToolKey::Letter('c') => { if self.last_sharp_arc(cx).is_none() { return vec![]; diff --git a/crates/tools/src/quickpen/edit.rs b/crates/tools/src/quickpen/edit.rs index be23386268..8ba8f970ce 100644 --- a/crates/tools/src/quickpen/edit.rs +++ b/crates/tools/src/quickpen/edit.rs @@ -19,6 +19,9 @@ use crate::draw2::{anchor_in, segment_in, shown_paths}; use crate::guides::{PointSnap, Targets}; use crate::{Action, Cursor, Overlay, ToolContext}; +/// The notice the tool asks for after each preview of a drag, to see the document's revision then. +pub(super) const MOVED: &str = "moved"; + /// What a press holds. #[derive(Clone, Copy, Debug, PartialEq)] pub(super) enum Grab { @@ -83,6 +86,11 @@ pub(super) struct Edit { pub(super) began: bool, /// Whether the last drag left what the press holds away from where it started. pub(super) moved: bool, + /// The document's revision ([`ToolContext::revision`]) after the drag's last preview. + pub(super) revision: Option<(u64, u64)>, + /// Whether another command changed the document or the selection during the drag: the drag + /// then previews no more, and its undo step keeps that edit with the move as last shown. + pub(super) interrupted: bool, /// The grabbed path as the document had it when the press went down. pressed: Option>, snap: Option, @@ -92,7 +100,16 @@ pub(super) struct Edit { impl Edit { pub(super) fn new(cx: &ToolContext, grab: Grab, start: Point, shift: bool) -> Self { let pressed = shared_node(cx.doc, grab.id()).cloned(); - Self { grab, start, shift, began: false, moved: false, pressed, snap: None, guides: vec![] } + Self { grab, start, shift, began: false, moved: false, revision: None, interrupted: false, pressed, snap: None, guides: vec![] } + } + + /// Whether the drag began and still previews: no other command changed the document or the + /// selection since its last preview. + pub(super) fn open(&mut self, cx: &ToolContext) -> bool { + if self.began && self.revision.is_some_and(|r| r != cx.revision) { + self.interrupted = true; + } + self.began && !self.interrupted } /// Whether the grabbed path is as the document had it when the press went down. @@ -106,9 +123,13 @@ impl Edit { /// Moves what the press holds by the drag to `p`. The first move selects the anchor, or the /// segment, unless it is already selected, and begins the undo step; a drag that starts on /// one of several selected anchors moves them all. When the grabbed path changed after the - /// press went down, the drag does not begin. + /// press went down, the drag does not begin, and after another command's edit during the + /// drag it moves nothing more. pub(super) fn drag(&mut self, cx: &ToolContext, p: Point) -> Vec { let mut out = vec![]; + if self.began && !self.open(cx) { + return out; + } if !self.began { let id = self.grab.id(); if !self.unchanged(cx) { @@ -153,11 +174,11 @@ impl Edit { } _ => p - self.start, }; - if !d.x.is_finite() || !d.y.is_finite() { - return out; + if d.x.is_finite() && d.y.is_finite() { + self.moved = d.x != 0.0 || d.y != 0.0; + out.push(Action::Preview("path.moveAnchors".into(), json!({"dx": d.x, "dy": d.y, "interpolate": true}))); } - self.moved = d.x != 0.0 || d.y != 0.0; - out.push(Action::Preview("path.moveAnchors".into(), json!({"dx": d.x, "dy": d.y, "interpolate": true}))); + out.push(Action::Notify(MOVED.into())); out } } From b9070d0013529471e8e08865b495afcd4905e293 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 21:25:20 -0800 Subject: [PATCH 042/151] Preferences: Revoke removes a script grant outside the automation read roots With automation read roots in force, script.grants names a script or a path outside them by its file name alone, and script.grants.revoke matches that name against the stored full path, so Revoke on such a row removed nothing and said the access was already revoked. Script File Access now reads the grants file, which is the app's own, with no roots in force. Each row keeps its script and path whole for script.grants.revoke and shows them as script.grants names them to the request that opened Preferences. ui.inspect, the reply of ui.dialog.set and the Reset Preferences question over the dialog name them the same way and leave out the whole values; ui.dialog.set's reply also leaves out the folder preferences outside the read roots, as ui.inspect does. --- crates/ui-egui/src/control.rs | 31 ++++++++--- crates/ui-egui/src/prefs_dialog.rs | 2 +- .../ui-egui/src/prefs_dialog/script_access.rs | 52 ++++++++++++++++--- crates/ui-egui/src/prefs_dialog/tests.rs | 52 +++++++++++++++++++ docs/target-app-parity.md | 2 +- 5 files changed, 123 insertions(+), 16 deletions(-) diff --git a/crates/ui-egui/src/control.rs b/crates/ui-egui/src/control.rs index 218312750d..5035a00d04 100644 --- a/crates/ui-egui/src/control.rs +++ b/crates/ui-egui/src/control.rs @@ -1152,7 +1152,8 @@ fn leave_out_unreadable_values(v: &mut Value, place: ParamsPlace) { /// Takes out of `ui.inspect`'s copy of the UI state the paths the request may not read: recent files, /// a library panel's file, folder preferences (saved, and in an open Preferences dialog) and the paths /// in recorded actions' steps and in the item an open Insert Menu Item dialog picked, outside the -/// read root. The file selected in an open JavaScript Files dialog is named as `svgInteractivity.info` +/// read root. An open Preferences dialog's kept script file access names its scripts and paths as +/// `script.grants` does. The file selected in an open JavaScript Files dialog is named as `svgInteractivity.info` /// names the active document's linked files. The UI state itself is not changed. fn leave_out_unreadable_paths(app: &VectorcraftApp, ui: &mut serde_json::Map) { if let Some(Value::Array(files)) = ui.get_mut("recent_files") { @@ -1171,11 +1172,8 @@ fn leave_out_unreadable_paths(app: &VectorcraftApp, ui: &mut serde_json::Map) { + let preferences = dialog.get("kind").and_then(Value::as_str) == Some("preferences"); + let Some(Value::Object(fields)) = dialog.get_mut("fields") else { return }; + if preferences { + leave_out_unreadable_folders(fields); + crate::prefs_dialog::script_access::list_as_listed(fields); + } + if let Some(Value::Object(parent)) = fields.get_mut(crate::dialogs::PARENT) { + leave_out_unreadable_preferences(parent); + } +} + /// Takes out of `prefs` the folder preferences /// ([`vectorcraft_engine::cmd::prefscmds::FOLDER_PREFS`]) the request may not read ([`shows_folder`]). fn leave_out_unreadable_folders(prefs: &mut serde_json::Map) { @@ -1639,7 +1653,10 @@ fn dispatch(app: &mut VectorcraftApp, ctx: &egui::Context, req: &ControlRequest) return err(e); } } - let dialog = app.ui.dialog.as_ref().and_then(|d| serde_json::to_value(d).ok()).unwrap_or_default(); + let mut dialog = app.ui.dialog.as_ref().and_then(|d| serde_json::to_value(d).ok()).unwrap_or_default(); + if let Value::Object(shown) = &mut dialog { + leave_out_unreadable_preferences(shown); + } // `action` answers the dialog the fields were just set in, within this request. match action { None => ok(dialog), diff --git a/crates/ui-egui/src/prefs_dialog.rs b/crates/ui-egui/src/prefs_dialog.rs index 19aa7d9e66..a23ef884a5 100644 --- a/crates/ui-egui/src/prefs_dialog.rs +++ b/crates/ui-egui/src/prefs_dialog.rs @@ -13,7 +13,7 @@ use crate::theme::{self, Accent, Brightness, Scheme, Tokens}; use crate::{VectorcraftApp, widgets}; mod descriptions; -mod script_access; +pub(crate) mod script_access; /// UI-only fields shown in the dialog (backed by `UiState`, not engine prefs). pub const UI_FIELDS: &[(&str, &str, &str)] = &[ diff --git a/crates/ui-egui/src/prefs_dialog/script_access.rs b/crates/ui-egui/src/prefs_dialog/script_access.rs index abbe87386d..219145e60f 100644 --- a/crates/ui-egui/src/prefs_dialog/script_access.rs +++ b/crates/ui-egui/src/prefs_dialog/script_access.rs @@ -27,12 +27,27 @@ const ROW_HEIGHT: f32 = 30.0; /// The list's height before it scrolls. const LIST_HEIGHT: f32 = 180.0; +/// The keys of a row that hold its script and path as it shows them, each with the key that holds +/// it whole. +const WHOLE: [(&str, &str); 2] = [("script", "wholeScript"), ("path", "wholePath")]; + /// The kept grants (`script.grants`) as the rows of the field [`ROWS`] in the Preferences dialog's -/// `fields`. Where the session keeps no grants, the field is removed. +/// `fields`. Where the session keeps no grants, the field is removed. The grants file is the app's +/// own, so it is read with no automation roots in force: each row keeps its script and path whole +/// (`wholeScript` and `wholePath`) for `script.grants.revoke`, and shows them (`script` and `path`) +/// as `script.grants` names them to the request that opened the dialog ([`as_listed`]). pub(super) fn load(app: &mut VectorcraftApp, fields: &mut Map) { - match app.session.execute("script.grants", &json!({})) { + match vectorcraft_engine::file_access::unconfined(|| app.session.execute("script.grants", &json!({}))) { Ok(v) if !v["file"].is_null() => { - fields.insert(ROWS.into(), Value::Array(rows(&v["grants"]))); + let mut rows = rows(&v["grants"]); + for row in rows.iter_mut().filter_map(Value::as_object_mut) { + for (shown, whole) in WHOLE { + let Some(path) = row.get(shown).and_then(Value::as_str).map(str::to_string) else { continue }; + row.insert(shown.into(), json!(as_listed(&path))); + row.insert(whole.into(), json!(path)); + } + } + fields.insert(ROWS.into(), Value::Array(rows)); } _ => { fields.remove(ROWS); @@ -77,6 +92,29 @@ pub(super) fn shown(path: &str) -> String { permissions::display_text(path, MAX_SHOWN_PATH) } +/// A kept script or path as `script.grants` names it to the request being served: whole where that +/// request may read it, else its file name alone (empty for a path that ends in no name). +pub(crate) fn as_listed(path: &str) -> &str { + if vectorcraft_engine::file_access::check_read(path).is_ok() { + return path; + } + let name = path.rsplit(vectorcraft_doc::links::path_separators(path)).next().unwrap_or_default(); + if matches!(name, "." | "..") { "" } else { name } +} + +/// The rows of `ROWS` in a copy of the Preferences dialog's `fields` (`ui.inspect` and +/// `ui.dialog.set`'s reply) with each script and path as [`as_listed`] gives it to the request being +/// served, and without the whole ones. +pub(crate) fn list_as_listed(fields: &mut Map) { + for row in fields.get_mut(ROWS).and_then(Value::as_array_mut).into_iter().flatten().filter_map(Value::as_object_mut) { + for (shown, whole) in WHOLE { + if let Some(path) = row.remove(whole).as_ref().and_then(Value::as_str) { + row.insert(shown.into(), json!(as_listed(path))); + } + } + } +} + /// The label of a row's access. fn access_label(access: &str) -> &'static str { match access { @@ -106,7 +144,7 @@ pub(super) fn show(ui: &mut egui::Ui, app: &mut VectorcraftApp, d: &mut Dialog) } let mut lines = Vec::with_capacity(rows.len() * 2); for (i, row) in rows.iter().enumerate() { - if i == 0 || rows[i - 1]["script"] != row["script"] { + if i == 0 || rows[i - 1]["wholeScript"] != row["wholeScript"] { lines.push(Line::Script(i)); } lines.push(Line::Row(i)); @@ -178,13 +216,13 @@ pub(super) fn show(ui: &mut egui::Ui, app: &mut VectorcraftApp, d: &mut Dialog) } } -/// Revoke on the row `i` of the Preferences dialog `d`: every kept grant of its script and path is -/// removed (`script.grants.revoke`), the rows are read again and the row now at `i`, or the last +/// Revoke on the row `i` of the Preferences dialog `d`: every kept grant of its script and path, +/// whole, is removed (`script.grants.revoke`), the rows are read again and the row now at `i`, or the last /// row, takes the keyboard focus. The status bar says what happened; on an error the rows stay as /// they were. pub(super) fn revoke(app: &mut VectorcraftApp, d: &mut Dialog, i: usize) { let Some(row) = d.fields.get(ROWS).and_then(|rows| rows.get(i)).cloned() else { return }; - match app.run("script.grants.revoke", json!({"script": row["script"], "path": row["path"]})) { + match app.run("script.grants.revoke", json!({"script": row["wholeScript"], "path": row["wholePath"]})) { Ok(v) => { load(app, &mut d.fields); let left = d.fields.get(ROWS).and_then(Value::as_array).map_or(0, Vec::len); diff --git a/crates/ui-egui/src/prefs_dialog/tests.rs b/crates/ui-egui/src/prefs_dialog/tests.rs index f201c553dc..94d710dead 100644 --- a/crates/ui-egui/src/prefs_dialog/tests.rs +++ b/crates/ui-egui/src/prefs_dialog/tests.rs @@ -3129,6 +3129,58 @@ fn script_file_access_shows_none_and_a_revoke_of_a_removed_row() { assert!(!text.contains("No script has kept file access."), "{text}"); } +/// Preferences opened with a read root in force shows a script and a path outside it by their file +/// names alone, as `script.grants` lists them, and `ui.inspect`, `ui.dialog.set`'s reply and the +/// Reset Preferences question over the dialog name them the same way; Revoke still removes that +/// pair's kept grants, both with the root in force and without it. +#[test] +fn script_file_access_revokes_a_pair_outside_the_read_roots() { + let dir = std::env::temp_dir().join("vc-ui-prefs-grants-nowhere"); + let (script, path) = (dir.join("a.jsx"), dir.join("out.txt")); + let root = temp_folder("grants-root-in"); + let roots = vectorcraft_engine::file_access::AutomationRoots::new(&[root.as_path()], &[]).unwrap(); + for confined in [true, false] { + let (mut a, store) = app_with_grants("grants-outside-roots", json!([grant(&script, &path, "1", false, false)])); + let (shown, inspected, set, under) = vectorcraft_engine::file_access::confine(roots.as_ref(), || { + open(&mut a, Some("General")); + let shown = access_rows(&a); + let ctx = egui::Context::default(); + let inspected = crate::control::inspect(&a, &ctx); + let (req, _) = crate::control::ControlRequest::new("ui.dialog.set", json!({"field": "unitsGeneral", "value": "points"})); + let crate::control::Outcome::Done(set) = crate::control::handle(&mut a, &ctx, &req) else { panic!("expected an immediate reply") }; + let kept = a.ui.dialog.clone(); + crate::dialogs::confirm::ask_reset_prefs(&mut a); + let under = crate::control::inspect(&a, &ctx); + a.ui.dialog = kept; + (shown, inspected, set, under) + }); + assert_eq!(shown, [("a.jsx".to_string(), "out.txt".to_string(), "read".to_string(), 1)]); + // The person's frame draws the rows as the request that opened the dialog was shown them. + let texts = script_access_in_view(&mut a, &fonts_context(), "out.txt"); + let whole = dir.to_string_lossy(); + assert!(texts.iter().any(|(t, _)| t == "a.jsx") && !texts.iter().any(|(t, _)| t.contains(&*whole)), "{texts:?}"); + let listed = json!({"script": "a.jsx", "path": "out.txt"}); + for (reply, row) in [ + (&inspected, &inspected["ui"]["dialog"]["fields"][script_access::ROWS][0]), + (&set, &set["result"]["fields"][script_access::ROWS][0]), + (&under, &under["ui"]["dialog"]["fields"][crate::dialogs::PARENT]["fields"][script_access::ROWS][0]), + ] { + assert_eq!(json!({"script": row["script"], "path": row["path"]}), listed, "{reply}"); + assert!(row["wholeScript"].is_null() && row["wholePath"].is_null(), "{reply}"); + } + let mut d = a.ui.dialog.clone().unwrap(); + let roots_now = if confined { roots.as_ref() } else { None }; + vectorcraft_engine::file_access::confine(roots_now, || script_access::revoke(&mut a, &mut d, 0)); + a.ui.dialog = Some(d); + assert_eq!(a.ui.status, "Script file access revoked", "confined: {confined}"); + assert!(access_rows(&a).is_empty(), "confined: {confined}"); + let stored: Value = serde_json::from_slice(&std::fs::read(&store).unwrap()).unwrap(); + assert!(stored["grants"].as_array().is_some_and(Vec::is_empty), "confined: {confined}: {stored}"); + let _ = std::fs::remove_dir_all(store.parent().unwrap()); + } + let _ = std::fs::remove_dir_all(&root); +} + /// A grants file that is not well formed or is larger than may be read is refused: Revoke shows /// the error, grants nothing and leaves the file and the rows as they were. #[test] diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 8b38a9d408..9b0a072347 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1041,7 +1041,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - Scripts: `$.line` is the line of the running script, counting from 1, and `$.stack` is the current stack trace ([the help page](https://extendscript.docsforadobe.dev/extendscript-tools-features/dollar-object/)). VectorCraft's own rules: both count lines in the file the code is in (the script, a file it included, a file `$.evalFile` ran, or the file of an earlier run of the named engine), and `$.stack` writes each frame as `name@file:line`, outermost first; code that `eval` or `Function` compiled keeps its own line in `[eval]`, and code whose place the engine no longer keeps is at line 0 of `[unknown]`. `crates/engine/src/tests/script_include.rs`, `crates/engine/src/tests/script_engines.rs`, `crates/js/src/extension_tests.rs`. - Scripts: `File` and `Folder` ([File object](https://extendscript.docsforadobe.dev/file-system-access/file-object/), [Folder object](https://extendscript.docsforadobe.dev/file-system-access/folder-object/)) name files and folders by platform or URI path, with `name`, `fsName`, `absoluteURI`, `relativeURI`, `parent`, `Folder.current` and `encode`/`decode`, and read them: `exists`, `length`, the dates, `getFiles` with a mask or a function, and `open('r')` with `read`, `readln`, `readch`, `seek`, `tell` and `close`, decoding by byte order mark, `encoding`, UTF-8 or CP1252. VectorCraft's own rules: a script reads only in its own folder and below (and inside the automation read roots when they are set); any other path and a network or device path are refused before anything is looked up, and a link that leads out is refused as well (`false` or `null`, with `error` set); a file is read whole up to 8 MiB and a run reads up to 32 MiB; `execute` is not available. `crates/engine/src/tests/script_io.rs`. - Scripts: `File` and `Folder` write ([File object](https://extendscript.docsforadobe.dev/file-system-access/file-object/), [Folder object](https://extendscript.docsforadobe.dev/file-system-access/folder-object/)): `open('w')`, `open('e')` and `open('a')` with `write` and `writeln` by `lineFeed`, `copy`, `remove` (a folder only when empty), `rename`, `folder.create()`, the `length` and `readonly` setters, and `File.openDialog`, `File.saveDialog`, `Folder.selectDialog`, `openDlg`, `saveDlg` and `selectDlg`, with a `filter` of file types or a filter function and `multiSelect`. VectorCraft's own rules: a script writes only in `Folder.temp` (one for the run, deleted when it ends), its own `Folder.userData` next to the settings, and what a person allowed it in a file dialog, once or always; Always keeps the grant for that script file with that text by its SHA-256 and for the sources the run evaluated (`$.evalFile`, `eval`, `Function`), so a run that evaluates other code, or whose named engine holds other code, loses it first; `script.grants` lists the grants and `script.grants.revoke` removes them; the settings folder is kept out of every grant; the commands a script runs with `vc.run` read and write only in the same places and the open documents' own files; a run with nobody to ask gets `null` from the dialogs; a file is written at close or when the run ends, 8 MiB a file and 32 MiB a run, and named in `written`, also after a run that failed. `crates/engine/src/tests/script_io.rs`. - - Scripts: Preferences › General › Script File Access lists the file access kept with Always Allow This Script (`script.grants`), one row for each script and path with its widest access (read file, read and write file, or read and write folder), and its Revoke button removes every kept version of that script and path (`script.grants.revoke`), so the next run asks again. Paths show control and bidirectional characters as escapes; a grants file that is not well formed or is over 4 MiB makes Revoke show its error and leaves the file as it was. VectorCraft's own addition. `crates/ui-egui/src/prefs_dialog/tests.rs` (`script_file_access_*`). + - Scripts: Preferences › General › Script File Access lists the file access kept with Always Allow This Script (`script.grants`), one row for each script and path with its widest access (read file, read and write file, or read and write folder), and its Revoke button removes every kept version of that script and path (`script.grants.revoke`), so the next run asks again. Paths show control and bidirectional characters as escapes, and a script or path outside the automation read roots in force when Preferences opens shows by its file name, as `script.grants` lists it, and Revoke still removes it; a grants file that is not well formed or is over 4 MiB makes Revoke show its error and leaves the file as it was. VectorCraft's own addition. `crates/ui-egui/src/prefs_dialog/tests.rs` (`script_file_access_*`). - Scripts: the `hidden` setter and `createAlias(target)` ([File object](https://extendscript.docsforadobe.dev/file-system-access/file-object/)), with setting `hidden`, `rename` and `remove` acting on an alias itself ([Using File and Folder objects](https://extendscript.docsforadobe.dev/file-system-access/using-file-and-folder-objects/)). VectorCraft's own rules: on Unix a name that starts with a dot is hidden, so setting `hidden` renames the file with one dot added or its leading dots taken off, and both names must be places the script may write; `createAlias` makes a symbolic link to the real path of a file the script may read, in a place it may write where nothing is, a link that leads nowhere included; a link is checked again each time it is used; on Windows both set `error` and change nothing. `crates/engine/src/tests/script_io.rs`. - Scripts: `#strict on` (and `//@strict on`) runs the script with the checks the [`$` object](https://extendscript.docsforadobe.dev/extendscript-tools-features/dollar-object/) help page gives for `$.strict`: an assignment to a read-only property throws a `TypeError`, and so does a new property on an object that takes none. VectorCraft's own rules: a getter-only property counts as read-only, the objects that take no new properties are the non-extensible ones (`Object.preventExtensions`, `seal`, `freeze`, and the frozen `vc` and `$` objects), the last `#strict` line of the script and its includes sets the whole run, a file `$.evalFile` runs keeps its own line's checks for its code, and the rest of ES5 strict mode stays with `'use strict'`. Without the line, runs are unchanged. `crates/engine/src/tests/script_include.rs` (`strict_on_*`, `strict_mode_in_eval_file_is_scoped`), `crates/js/src/interp_tests.rs` (`strict_writes_are_separate_from_es5_strict`). - Scripts folder: File › Scripts lists the `.js` and `.jsx` files of the `Scripts` folder next to the preferences, each named after its file without the extension, with each subfolder as a submenu, above Check Script… and Other Script… (https://helpx.adobe.com/illustrator/desktop/automate-visualize-data/automate-actions/install-and-run-scripts.html). VectorCraft's own rules: the folder is read again when the window becomes active and when the File menu opens (in the macOS menu bar, when any of its menus opens, and the new listing shows the next time the menu opens), links are not followed, and one read stops at 2,048 entries, 512 scripts, 128 subfolders, 4 levels or 250 ms. `script.listInstalled` returns the listing. `crates/engine/src/tests/script_folder.rs`, `crates/ui-egui/src/tests/scripts_menu.rs`. From 357133cef1bfeed76a808ba4ad5b78b138a0e564 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 21:51:20 -0800 Subject: [PATCH 043/151] Quick Pen: a selection change during a press stops it When another command changes the selection while a press on an anchor or a segment is down, the release no longer selects an anchor, goes on drawing from an open end, or moves anything. Choosing another tool during a drag that came back to where it started now records no undo step. --- crates/engine/src/tests/quickpen.rs | 31 ++++++++++++++++++++++++ crates/tools/src/quickpen.rs | 20 +++++++--------- crates/tools/src/quickpen/edit.rs | 37 ++++++++++++++++++++++++----- 3 files changed, 70 insertions(+), 18 deletions(-) diff --git a/crates/engine/src/tests/quickpen.rs b/crates/engine/src/tests/quickpen.rs index 39cc07a530..e9181b03d7 100644 --- a/crates/engine/src/tests/quickpen.rs +++ b/crates/engine/src/tests/quickpen.rs @@ -676,6 +676,37 @@ fn a_drag_back_to_its_start_records_no_undo_step() { assert_eq!(points(&s), [pt(100.0, 100.0), pt(200.0, 100.0), pt(300.0, 100.0)], "press at {at:?}"); assert_eq!(undo_steps(&s), undo, "press at {at:?}"); } + // Choosing another tool during such a drag records none either. + let v = view(); + s.pointer(&PointerEvent::new(PointerKind::Down, 200.0, 100.0), v).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Drag, 200.0, 150.0), v).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Drag, 200.0, 100.0), v).unwrap(); + s.select_tool("selection", v).unwrap(); + assert_eq!(points(&s), [pt(100.0, 100.0), pt(200.0, 100.0), pt(300.0, 100.0)]); + assert_eq!(undo_steps(&s), undo); +} + +/// When another command changes the selection while the press is down, neither a click nor a drag +/// selects or moves the anchor the press found. +#[test] +fn a_selection_change_during_an_edit_press_stops_it() { + let mut s = session(); + let id = selected_quick_pen_path(&mut s, (100.0, 100.0), json!([{"x": 200, "y": 100}, {"x": 300, "y": 100}])); + let v = view(); + for drag in [false, true] { + s.execute("select.set", &json!({"ids": [id.0]})).unwrap(); + let undo = undo_steps(&s); + s.pointer(&PointerEvent::new(PointerKind::Down, 200.0, 100.0), v).unwrap(); + s.execute("select.none", &json!({})).unwrap(); + let y = if drag { 150.0 } else { 100.0 }; + if drag { + s.pointer(&PointerEvent::new(PointerKind::Drag, 200.0, y), v).unwrap(); + } + s.pointer(&PointerEvent::new(PointerKind::Up, 200.0, y), v).unwrap(); + assert!(s.doc().unwrap().selection.objects.is_empty(), "drag: {drag}"); + assert_eq!(points(&s), [pt(100.0, 100.0), pt(200.0, 100.0), pt(300.0, 100.0)], "drag: {drag}"); + assert_eq!(undo_steps(&s), undo, "drag: {drag}"); + } } /// When another command edits the path while the press is down, neither a drag nor a release past diff --git a/crates/tools/src/quickpen.rs b/crates/tools/src/quickpen.rs index bdb80c2a5b..62819f793f 100644 --- a/crates/tools/src/quickpen.rs +++ b/crates/tools/src/quickpen.rs @@ -499,17 +499,14 @@ impl QuickPenTool { /// go past the drag distance after shorter drag events, moves what it holds to `p` and ends /// its undo step. A click on an end of an open path goes on drawing from it, a click on another /// anchor selects it alone (with Shift, adds it to the selected anchors or takes it out), and a - /// click on a segment starts a new path there. A click whose path another command edited while - /// the press was down does nothing. + /// click on a segment starts a new path there. A click whose path or selection another command + /// changed while the press was down does nothing. fn release_edit(&mut self, cx: &ToolContext, mut e: Edit, p: Point) -> Vec { if e.began || p.distance(e.start) >= cx.tol(DRAG_PX) { let mut out = e.drag(cx, p); - // A drag that could not begin (its path changed under the press) has no step to end. - // One that came back to where it started records none, unless another command's - // edit during the drag is in the step. - if e.began { - out.push(if e.moved || e.interrupted { Action::Commit } else { Action::Cancel }); - } + // A drag that could not begin (its path or the selection changed under the press) has + // no step to end. + out.extend(e.finish(cx)); return out; } if !e.unchanged(cx) { @@ -734,14 +731,13 @@ impl Tool for QuickPenTool { } } - fn deactivate(&mut self, _cx: &ToolContext) -> Vec { + fn deactivate(&mut self, cx: &ToolContext) -> Vec { self.drawing = None; self.snap.clear(); - let moved = self.edit.take().is_some_and(|e| e.began); + let moved = self.edit.take().and_then(|mut e| e.finish(cx)); match self.press.take() { Some(pr) if pr.begun => vec![Action::Commit], - _ if moved => vec![Action::Commit], - _ => vec![], + _ => moved.into_iter().collect(), } } diff --git a/crates/tools/src/quickpen/edit.rs b/crates/tools/src/quickpen/edit.rs index 8ba8f970ce..2620118b91 100644 --- a/crates/tools/src/quickpen/edit.rs +++ b/crates/tools/src/quickpen/edit.rs @@ -93,6 +93,8 @@ pub(super) struct Edit { pub(super) interrupted: bool, /// The grabbed path as the document had it when the press went down. pressed: Option>, + /// The selection when the press went down. + pressed_selection: Selection, snap: Option, pub(super) guides: Vec, } @@ -100,7 +102,20 @@ pub(super) struct Edit { impl Edit { pub(super) fn new(cx: &ToolContext, grab: Grab, start: Point, shift: bool) -> Self { let pressed = shared_node(cx.doc, grab.id()).cloned(); - Self { grab, start, shift, began: false, moved: false, revision: None, interrupted: false, pressed, snap: None, guides: vec![] } + let pressed_selection = cx.selection.clone(); + Self { + grab, + start, + shift, + began: false, + moved: false, + revision: None, + interrupted: false, + pressed, + pressed_selection, + snap: None, + guides: vec![], + } } /// Whether the drag began and still previews: no other command changed the document or the @@ -112,18 +127,28 @@ impl Edit { self.began && !self.interrupted } - /// Whether the grabbed path is as the document had it when the press went down. + /// What ends a drag that began when the press is let go: a commit, or a cancel when the drag + /// came back to where it started and no other command's edit is in its undo step. + pub(super) fn finish(&mut self, cx: &ToolContext) -> Option { + if !self.began { + return None; + } + Some(if self.open(cx) && !self.moved { Action::Cancel } else { Action::Commit }) + } + + /// Whether the grabbed path and the selection are as they were when the press went down. pub(super) fn unchanged(&self, cx: &ToolContext) -> bool { - match (cx.doc.node(self.grab.id()), self.pressed.as_ref()) { + let path = match (cx.doc.node(self.grab.id()), self.pressed.as_ref()) { (Some(now), Some(then)) => same_node(now, then), _ => false, - } + }; + path && *cx.selection == self.pressed_selection } /// Moves what the press holds by the drag to `p`. The first move selects the anchor, or the /// segment, unless it is already selected, and begins the undo step; a drag that starts on - /// one of several selected anchors moves them all. When the grabbed path changed after the - /// press went down, the drag does not begin, and after another command's edit during the + /// one of several selected anchors moves them all. When the grabbed path or the selection + /// changed after the press went down, the drag does not begin, and after another command's edit during the /// drag it moves nothing more. pub(super) fn drag(&mut self, cx: &ToolContext, p: Point) -> Vec { let mut out = vec![]; From ce0f57826830c8926a96b61e7eed711f11e5c72b Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 22:21:07 -0800 Subject: [PATCH 044/151] Preferences: Script File Access shows why the grants file cannot be read When the grants file was not well formed, was not JSON, was over 4 MiB or its lock could not be taken, script.grants listed no grants and Preferences said "No script has kept file access." while the file could still hold grants. script.grants now adds error, with the reason, when the file is there and cannot be read or changed, and still lists the well-formed grants it can read. Script File Access shows that error in place of the empty-list line, with any rows that could be read. The grants file is not written. The message has rows in the 25 complete-message catalogs, and the params text and docs/mcp.md describe the field. --- crates/engine/src/cmd/scripts.rs | 10 ++++--- crates/engine/src/script/files.rs | 17 +++++++++--- crates/engine/src/tests/script_io.rs | 8 +++--- crates/ui-egui/src/i18n/ca.tsv | 1 + crates/ui-egui/src/i18n/cs.tsv | 1 + crates/ui-egui/src/i18n/da.tsv | 1 + crates/ui-egui/src/i18n/de.tsv | 1 + crates/ui-egui/src/i18n/el.tsv | 1 + crates/ui-egui/src/i18n/es.tsv | 1 + crates/ui-egui/src/i18n/fi.tsv | 1 + crates/ui-egui/src/i18n/fr.tsv | 1 + crates/ui-egui/src/i18n/hi.tsv | 1 + crates/ui-egui/src/i18n/hu.tsv | 1 + crates/ui-egui/src/i18n/id.tsv | 1 + crates/ui-egui/src/i18n/it.tsv | 1 + crates/ui-egui/src/i18n/ja.tsv | 1 + crates/ui-egui/src/i18n/ka.tsv | 1 + crates/ui-egui/src/i18n/ko.tsv | 1 + crates/ui-egui/src/i18n/nl.tsv | 1 + crates/ui-egui/src/i18n/pl.tsv | 1 + crates/ui-egui/src/i18n/pt-br.tsv | 1 + crates/ui-egui/src/i18n/ru.tsv | 1 + crates/ui-egui/src/i18n/sv.tsv | 1 + crates/ui-egui/src/i18n/tests.rs | 1 + crates/ui-egui/src/i18n/tr.tsv | 1 + crates/ui-egui/src/i18n/uk.tsv | 1 + crates/ui-egui/src/i18n/vi.tsv | 1 + crates/ui-egui/src/i18n/zh-hans.tsv | 1 + crates/ui-egui/src/i18n/zh-hant.tsv | 1 + .../ui-egui/src/prefs_dialog/script_access.rs | 24 ++++++++++++++--- crates/ui-egui/src/prefs_dialog/tests.rs | 26 +++++++++++++++++++ docs/mcp.md | 8 +++--- docs/target-app-parity.md | 2 +- 33 files changed, 105 insertions(+), 16 deletions(-) diff --git a/crates/engine/src/cmd/scripts.rs b/crates/engine/src/cmd/scripts.rs index dc33c46ab1..44b8b7f432 100644 --- a/crates/engine/src/cmd/scripts.rs +++ b/crates/engine/src/cmd/scripts.rs @@ -95,7 +95,7 @@ pub fn specs() -> Vec { "List Script File Permissions", [], None, - "{} the file access people allowed scripts with Always in a file dialog, kept in Script Grants.json next to the settings: each for one script file with one text and the files it includes (their SHA-256), so a changed or moved script, or a changed included file, has none, and with the SHA-256 of each source the run that kept it evaluated (files $.evalFile ran, strings given to eval and Function; at most 256), so a run loses it before it evaluates other code, or when its named engine holds code the grant was not kept for; at most 4096 → {grants: [{script: the script file's path, sha256, code: [SHA-256 of each evaluated source, of its UTF-16 code units in little-endian order], path: the file or folder allowed, write: it may be written, folder: the grant is a folder's, with everything in it (a file's grant is its own path only)}], file: the grants file's path | null (a session without a settings folder, and the web)}", + "{} the file access people allowed scripts with Always in a file dialog, kept in Script Grants.json next to the settings: each for one script file with one text and the files it includes (their SHA-256), so a changed or moved script, or a changed included file, has none, and with the SHA-256 of each source the run that kept it evaluated (files $.evalFile ran, strings given to eval and Function; at most 256), so a run loses it before it evaluates other code, or when its named engine holds code the grant was not kept for; at most 4096 → {grants: [{script: the script file's path, sha256, code: [SHA-256 of each evaluated source, of its UTF-16 code units in little-endian order], path: the file or folder allowed, write: it may be written, folder: the grant is a folder's, with everything in it (a file's grant is its own path only)}], file: the grants file's path | null (a session without a settings folder, and the web), error?: why the grants file cannot be read or changed, when it is there and cannot be read, is over 4 MiB, is not a version 1 grants file, holds a grant that is not well formed or more than 4096 grants, or its lock cannot be taken (grants then lists the well-formed grants that can still be read, if any, and script.grants.revoke fails)}", always, grants ), @@ -369,7 +369,7 @@ fn grants(s: &mut Session, _: &Value) -> Result { let Some(dir) = s.script_data_dir() else { return Ok(json!({"grants": [], "file": null})) }; let file = dir.with_file_name(script::files::GRANTS_FILE); // A script or a granted path outside the automation read roots is named by its file name alone. - let mut grants = script::files::stored_grants(dir); + let (mut grants, unreadable) = script::files::stored_grants(dir); for g in &mut grants { for key in ["script", "path"] { if let Some(name) = g[key].as_str().and_then(hidden_name) { @@ -378,7 +378,11 @@ fn grants(s: &mut Session, _: &Value) -> Result { } } let file = file.to_string_lossy(); - Ok(json!({"grants": grants, "file": super::fileio::shown_path(&file)})) + let mut listed = json!({"grants": grants, "file": super::fileio::shown_path(&file)}); + if let Some(e) = unreadable { + listed["error"] = json!(EngineError::Other(format!("the script file permissions could not be read: {e}")).to_string()); + } + Ok(listed) } fn grants_revoke(s: &mut Session, p: &Value) -> Result { diff --git a/crates/engine/src/script/files.rs b/crates/engine/src/script/files.rs index 94ef3bdf9e..191f1c52e0 100644 --- a/crates/engine/src/script/files.rs +++ b/crates/engine/src/script/files.rs @@ -1062,9 +1062,20 @@ fn lock_store(_: &Path) -> std::io::Result { } /// The grants the grants file beside the data folder `data_dir` keeps: each script, the SHA-256 of -/// its text, the path and whether it may be written (`script.grants`). -pub(crate) fn stored_grants(data_dir: &Path) -> Vec { - read_store(&data_dir.with_file_name(GRANTS_FILE)) +/// its text, the path and whether it may be written (`script.grants`), as [`read_store`] reads +/// them, and the error when the file is there and [`try_read_store`] refuses it (it cannot be read, +/// is too large, is not a grants file of this version, or holds a grant that is not well formed or +/// more grants than may be kept) or its lock cannot be taken, which also refuses a change. +pub(crate) fn stored_grants(data_dir: &Path) -> (Vec, Option) { + let store = data_dir.with_file_name(GRANTS_FILE); + let _lock = match lock_store(&store) { + Ok(lock) => lock, + Err(e) => return (Vec::new(), Some(e)), + }; + match try_read_store(&store) { + Ok(grants) => (grants, None), + Err(e) => (load_store(&store, false).unwrap_or_default(), Some(e)), + } } /// Removes from the grants file beside `data_dir` the grants of the script `script` and of the path diff --git a/crates/engine/src/tests/script_io.rs b/crates/engine/src/tests/script_io.rs index 25ccb3bcfb..6bcd6f7173 100644 --- a/crates/engine/src/tests/script_io.rs +++ b/crates/engine/src/tests/script_io.rs @@ -637,8 +637,8 @@ fn a_grants_change_without_its_lock_changes_nothing() { } /// Reading and changing the grants file wait for a lock another handle holds only for a bounded -/// number of tries: then a read gives no grants and a change fails with the file unchanged. A lock -/// released while it waits is taken. +/// number of tries: then a read gives no grants and the lock's error, and a change fails with the +/// file unchanged. A lock released while it waits is taken. #[test] fn a_grants_change_waits_for_a_held_lock_a_bounded_number_of_tries() { use crate::script::files::{LOCK_TRIES, WHILE_GRANTS_LOCKED, revoke_grants, stored_grants}; @@ -652,7 +652,9 @@ fn a_grants_change_waits_for_a_held_lock_a_bounded_number_of_tries() { let waits = std::rc::Rc::new(std::cell::Cell::new(0)); let counted = waits.clone(); WHILE_GRANTS_LOCKED.set(Some(Box::new(move || counted.set(counted.get() + 1)))); - assert_eq!(stored_grants(&data), Vec::::new(), "grants are not read without the lock"); + let (read, error) = stored_grants(&data); + assert_eq!(read, Vec::::new(), "grants are not read without the lock"); + assert_eq!(error.map(|e| e.kind()), Some(std::io::ErrorKind::TimedOut)); assert_eq!(waits.get(), LOCK_TRIES - 1); waits.set(0); let refused = revoke_grants(&data, None, None); diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index dc052e1209..fa4647a450 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -6627,6 +6627,7 @@ liquify-list-end {0}, {1} {0} i {1} @msg `answer` for a script's file dialog must be one of: once, always, deny, stop `answer` per al diàleg de fitxers d’un script ha de ser un d’aquests: once, always, deny, stop @msg choose a file or folder first, or deny trieu primer un fitxer o una carpeta, o denegueu @msg the script file permissions could not be saved: {e} no s’han pogut desar els permisos de fitxers dels scripts: {e} +@msg the script file permissions could not be read: {e} no s’han pogut llegir els permisos de fitxers dels scripts: {e} @msg this script's file access can be allowed only once l’accés als fitxers d’aquest script només es pot permetre una vegada @msg Only the person at the keyboard can allow a script's file access Només la persona al teclat pot permetre l’accés als fitxers d’un script @msg A script is given at most 2,048 files: the files picked after them were left out Un script rep com a màxim 2.048 fitxers: els fitxers triats després d’aquests s’han deixat fora diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index baa6fdb5a0..791e28bee2 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -5412,6 +5412,7 @@ liquify-list-end {0}, {1} {0} a {1} @msg `answer` for a script's file dialog must be one of: once, always, deny, stop `answer` pro dialog souboru skriptu musí být jedna z hodnot: once, always, deny, stop @msg choose a file or folder first, or deny nejprve vyberte soubor nebo složku, nebo odmítněte @msg the script file permissions could not be saved: {e} oprávnění skriptů k souborům nelze uložit: {e} +@msg the script file permissions could not be read: {e} oprávnění skriptů k souborům nelze přečíst: {e} @msg this script's file access can be allowed only once přístup tohoto skriptu k souborům lze povolit jen jednou @msg Only the person at the keyboard can allow a script's file access Přístup skriptu k souborům může povolit jen člověk u klávesnice @msg A script is given at most 2,048 files: the files picked after them were left out Skript dostane nejvýše 2 048 souborů: soubory vybrané po nich byly vynechány diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index 47c721d229..e805b3829c 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -99,6 +99,7 @@ @msg `answer` for a script's file dialog must be one of: once, always, deny, stop `answer` for et scripts fildialog skal være en af: once, always, deny, stop @msg choose a file or folder first, or deny vælg først en fil eller mappe, eller afvis @msg the script file permissions could not be saved: {e} scriptets filtilladelser kunne ikke gemmes: {e} +@msg the script file permissions could not be read: {e} scriptets filtilladelser kunne ikke læses: {e} @msg this script's file access can be allowed only once dette scripts filadgang kan kun tillades én gang @msg Only the person at the keyboard can allow a script's file access Kun personen ved tastaturet kan tillade et scripts filadgang @msg A script is given at most 2,048 files: the files picked after them were left out Et script får højst 2.048 filer: de filer, der blev valgt derefter, blev udeladt diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index a625e018ef..7b8ff241eb 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -4988,6 +4988,7 @@ liquify-list-end {0}, {1} {0} und {1} @msg `answer` for a script's file dialog must be one of: once, always, deny, stop `answer` für den Dateidialog eines Skripts muss einer der folgenden Werte sein: once, always, deny, stop @msg choose a file or folder first, or deny wählen Sie zuerst eine Datei oder einen Ordner aus oder lehnen Sie ab @msg the script file permissions could not be saved: {e} die Dateiberechtigungen der Skripte konnten nicht gespeichert werden: {e} +@msg the script file permissions could not be read: {e} die Dateiberechtigungen der Skripte konnten nicht gelesen werden: {e} @msg this script's file access can be allowed only once der Dateizugriff dieses Skripts kann nur einmal erlaubt werden @msg Only the person at the keyboard can allow a script's file access Nur die Person an der Tastatur kann den Dateizugriff eines Skripts erlauben @msg A script is given at most 2,048 files: the files picked after them were left out Ein Skript erhält höchstens 2.048 Dateien: Die danach ausgewählten Dateien wurden weggelassen diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index e428decf7c..6f13330deb 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -2825,6 +2825,7 @@ liquify-list-end {0}, {1} {0} και {1} @msg `answer` for a script's file dialog must be one of: once, always, deny, stop το `answer` για το παράθυρο διαλόγου αρχείων ενός σεναρίου πρέπει να είναι ένα από: once, always, deny, stop @msg choose a file or folder first, or deny επιλέξτε πρώτα ένα αρχείο ή έναν φάκελο, ή απορρίψτε @msg the script file permissions could not be saved: {e} δεν ήταν δυνατή η αποθήκευση των αδειών αρχείων των σεναρίων: {e} +@msg the script file permissions could not be read: {e} δεν ήταν δυνατή η ανάγνωση των αδειών αρχείων των σεναρίων: {e} @msg this script's file access can be allowed only once η πρόσβαση αυτού του σεναρίου σε αρχεία μπορεί να επιτραπεί μόνο μία φορά @msg Only the person at the keyboard can allow a script's file access Μόνο το άτομο στο πληκτρολόγιο μπορεί να επιτρέψει την πρόσβαση ενός σεναρίου σε αρχεία @msg A script is given at most 2,048 files: the files picked after them were left out Ένα σενάριο λαμβάνει το πολύ 2.048 αρχεία: τα αρχεία που επιλέχθηκαν μετά από αυτά παραλείφθηκαν diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index 6c9867b07c..be92272e97 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -5099,6 +5099,7 @@ liquify-list-end {0}, {1} {0}, {1} @msg `answer` for a script's file dialog must be one of: once, always, deny, stop `answer` para el cuadro de diálogo de archivo de un script debe ser uno de: once, always, deny, stop @msg choose a file or folder first, or deny elija primero un archivo o una carpeta, o deniegue @msg the script file permissions could not be saved: {e} no se pudieron guardar los permisos de archivos de los scripts: {e} +@msg the script file permissions could not be read: {e} no se pudieron leer los permisos de archivos de los scripts: {e} @msg this script's file access can be allowed only once el acceso a archivos de este script solo se puede permitir una vez @msg Only the person at the keyboard can allow a script's file access Solo la persona que está en el teclado puede permitir el acceso a archivos de un script @msg A script is given at most 2,048 files: the files picked after them were left out Un script recibe como máximo 2.048 archivos: los archivos elegidos después de ellos se omitieron diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index bba3adf2e7..360e2ecedf 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -5340,6 +5340,7 @@ liquify-list-end {0}, {1} {0} ja {1} @msg `answer` for a script's file dialog must be one of: once, always, deny, stop komentosarjan tiedostovalintaikkunan `answer`-arvon on oltava jokin seuraavista: once, always, deny, stop @msg choose a file or folder first, or deny valitse ensin tiedosto tai kansio tai estä @msg the script file permissions could not be saved: {e} komentosarjojen tiedostolupia ei voitu tallentaa: {e} +@msg the script file permissions could not be read: {e} komentosarjojen tiedostolupia ei voitu lukea: {e} @msg this script's file access can be allowed only once tämän komentosarjan tiedostojen käytön voi sallia vain kerran @msg Only the person at the keyboard can allow a script's file access Vain näppäimistön ääressä oleva ihminen voi sallia komentosarjan tiedostojen käytön @msg A script is given at most 2,048 files: the files picked after them were left out Komentosarja saa enintään 2 048 tiedostoa: niiden jälkeen valitut tiedostot jätettiin pois diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index f31aad04d4..347773645c 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -5058,6 +5058,7 @@ liquify-list-end {0}, {1} {0} et {1} @msg `answer` for a script's file dialog must be one of: once, always, deny, stop `answer` pour la boîte de dialogue de fichiers d’un script doit être l’une des valeurs : once, always, deny, stop @msg choose a file or folder first, or deny choisissez d’abord un fichier ou un dossier, ou refusez @msg the script file permissions could not be saved: {e} les autorisations d’accès aux fichiers des scripts n’ont pas pu être enregistrées : {e} +@msg the script file permissions could not be read: {e} les autorisations d’accès aux fichiers des scripts n’ont pas pu être lues : {e} @msg this script's file access can be allowed only once l’accès aux fichiers de ce script ne peut être autorisé qu’une fois @msg Only the person at the keyboard can allow a script's file access Seule la personne au clavier peut autoriser l’accès aux fichiers d’un script @msg A script is given at most 2,048 files: the files picked after them were left out Un script reçoit au plus 2 048 fichiers : les fichiers choisis après eux ont été laissés de côté diff --git a/crates/ui-egui/src/i18n/hi.tsv b/crates/ui-egui/src/i18n/hi.tsv index 9e8f4858ca..a89667cbf4 100644 --- a/crates/ui-egui/src/i18n/hi.tsv +++ b/crates/ui-egui/src/i18n/hi.tsv @@ -7774,6 +7774,7 @@ liquify-list-end {0}, {1} {0} और {1} @msg `answer` for a script's file dialog must be one of: once, always, deny, stop स्क्रिप्ट के फ़ाइल डायलॉग के लिए `answer` इनमें से एक होना चाहिए: once, always, deny, stop @msg choose a file or folder first, or deny पहले कोई फ़ाइल या फ़ोल्डर चुनें, या अस्वीकार करें @msg the script file permissions could not be saved: {e} स्क्रिप्ट की फ़ाइल अनुमतियाँ सेव नहीं की जा सकीं: {e} +@msg the script file permissions could not be read: {e} स्क्रिप्ट की फ़ाइल अनुमतियाँ पढ़ी नहीं जा सकीं: {e} @msg this script's file access can be allowed only once इस स्क्रिप्ट की फ़ाइल पहुँच केवल एक बार दी जा सकती है @msg Only the person at the keyboard can allow a script's file access किसी स्क्रिप्ट को फ़ाइल पहुँच केवल कीबोर्ड पर मौजूद व्यक्ति दे सकता है @msg A script is given at most 2,048 files: the files picked after them were left out किसी स्क्रिप्ट को अधिकतम 2,048 फ़ाइलें दी जाती हैं: उनके बाद चुनी गई फ़ाइलें छोड़ दी गईं diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index 3a99075b4c..c60f8f6b01 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -5930,6 +5930,7 @@ liquify-list-end {0}, {1} {0} és {1} @msg `answer` for a script's file dialog must be one of: once, always, deny, stop a parancsfájl fájlpárbeszédpaneléhez tartozó `answer` értéke a következők egyike kell legyen: once, always, deny, stop @msg choose a file or folder first, or deny először válasszon fájlt vagy mappát, vagy utasítsa el @msg the script file permissions could not be saved: {e} a parancsfájlok fájlengedélyeit nem sikerült menteni: {e} +@msg the script file permissions could not be read: {e} a parancsfájlok fájlengedélyeit nem sikerült beolvasni: {e} @msg this script's file access can be allowed only once ennek a parancsfájlnak a fájlhozzáférése csak egyszer engedélyezhető @msg Only the person at the keyboard can allow a script's file access Parancsfájl fájlhozzáférését csak a billentyűzetnél ülő személy engedélyezheti @msg A script is given at most 2,048 files: the files picked after them were left out Egy parancsfájl legfeljebb 2 048 fájlt kap: az ezek után kiválasztott fájlok kimaradtak diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index 853ee465b7..1be6b1859f 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -8768,6 +8768,7 @@ breakText Glyphs Glif @msg `answer` for a script's file dialog must be one of: once, always, deny, stop `answer` untuk dialog file skrip harus salah satu dari: once, always, deny, stop @msg choose a file or folder first, or deny pilih file atau folder terlebih dahulu, atau tolak @msg the script file permissions could not be saved: {e} izin file skrip tidak dapat disimpan: {e} +@msg the script file permissions could not be read: {e} izin file skrip tidak dapat dibaca: {e} @msg this script's file access can be allowed only once akses file skrip ini hanya dapat diizinkan sekali @msg Only the person at the keyboard can allow a script's file access Hanya orang yang berada di depan keyboard yang dapat mengizinkan akses file skrip @msg A script is given at most 2,048 files: the files picked after them were left out Skrip diberi paling banyak 2.048 file: file yang dipilih sesudahnya dihilangkan diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index 5a290e168a..b1f81d4037 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -5126,6 +5126,7 @@ liquify-list-end {0}, {1} {0} e {1} @msg `answer` for a script's file dialog must be one of: once, always, deny, stop `answer` per la finestra di dialogo dei file di uno script deve essere uno tra: once, always, deny, stop @msg choose a file or folder first, or deny scegli prima un file o una cartella, oppure nega @msg the script file permissions could not be saved: {e} impossibile salvare i permessi sui file degli script: {e} +@msg the script file permissions could not be read: {e} impossibile leggere i permessi sui file degli script: {e} @msg this script's file access can be allowed only once l'accesso ai file di questo script può essere consentito solo una volta @msg Only the person at the keyboard can allow a script's file access Solo la persona alla tastiera può consentire l’accesso ai file di uno script @msg A script is given at most 2,048 files: the files picked after them were left out Uno script riceve al massimo 2.048 file: i file scelti dopo questi sono stati esclusi diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index 6dc915f9aa..e5947dfed1 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -5961,6 +5961,7 @@ liquify-list-end {0}, {1} {0}、{1} @msg `answer` for a script's file dialog must be one of: once, always, deny, stop スクリプトのファイルダイアログの `answer` は once、always、deny、stop のいずれかにしてください @msg choose a file or folder first, or deny 先にファイルまたはフォルダーを選択するか、拒否してください @msg the script file permissions could not be saved: {e} スクリプトのファイル許可を保存できませんでした: {e} +@msg the script file permissions could not be read: {e} スクリプトのファイル許可を読み込めませんでした: {e} @msg this script's file access can be allowed only once このスクリプトのファイルアクセスは 1 回だけ許可できます @msg Only the person at the keyboard can allow a script's file access スクリプトのファイルアクセスを許可できるのはキーボードの前にいる人だけです @msg A script is given at most 2,048 files: the files picked after them were left out スクリプトに渡せるファイルは 2,048 個までのため、それ以降に選んだファイルは除外されました diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index 6932462a4e..0ff6c1e96e 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -8622,6 +8622,7 @@ liquify-list-end {0}, {1} {0} და {1} @msg `answer` for a script's file dialog must be one of: once, always, deny, stop სკრიპტის ფაილის დიალოგისთვის `answer` უნდა იყოს ერთ-ერთი: once, always, deny, stop @msg choose a file or folder first, or deny ჯერ აირჩიეთ ფაილი ან საქაღალდე, ან უარყავით @msg the script file permissions could not be saved: {e} სკრიპტების ფაილების ნებართვების შენახვა ვერ მოხერხდა: {e} +@msg the script file permissions could not be read: {e} სკრიპტების ფაილების ნებართვების წაკითხვა ვერ მოხერხდა: {e} @msg this script's file access can be allowed only once ამ სკრიპტის წვდომა ფაილებზე მხოლოდ ერთხელ შეიძლება დაიშვას @msg Only the person at the keyboard can allow a script's file access სკრიპტის წვდომას ფაილებზე მხოლოდ კლავიატურასთან მყოფი ადამიანი უშვებს @msg A script is given at most 2,048 files: the files picked after them were left out სკრიპტი იღებს მაქსიმუმ 2 048 ფაილს: მათ შემდეგ არჩეული ფაილები გამოტოვებულია diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index bddb440aee..62aadc98e0 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -5890,6 +5890,7 @@ liquify-list-end {0}, {1} {0} 및 {1} @msg `answer` for a script's file dialog must be one of: once, always, deny, stop 스크립트 파일 대화 상자의 `answer`는 once, always, deny, stop 중 하나여야 합니다 @msg choose a file or folder first, or deny 먼저 파일이나 폴더를 선택하거나 거부하세요 @msg the script file permissions could not be saved: {e} 스크립트 파일 권한을 저장할 수 없습니다: {e} +@msg the script file permissions could not be read: {e} 스크립트 파일 권한을 읽을 수 없습니다: {e} @msg this script's file access can be allowed only once 이 스크립트의 파일 접근은 한 번만 허용할 수 있습니다 @msg Only the person at the keyboard can allow a script's file access 스크립트의 파일 접근은 키보드 앞에 있는 사람만 허용할 수 있습니다 @msg A script is given at most 2,048 files: the files picked after them were left out 스크립트에는 파일이 최대 2,048개까지 전달됩니다: 그 뒤에 고른 파일은 제외되었습니다 diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index d00f9960df..11ee1ab242 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -101,6 +101,7 @@ @msg `answer` for a script's file dialog must be one of: once, always, deny, stop `answer` voor het bestandsdialoogvenster van een script moet een van deze waarden zijn: once, always, deny, stop @msg choose a file or folder first, or deny kies eerst een bestand of map, of weiger @msg the script file permissions could not be saved: {e} de toestemmingen voor scriptbestanden konden niet worden opgeslagen: {e} +@msg the script file permissions could not be read: {e} de toestemmingen voor scriptbestanden konden niet worden gelezen: {e} @msg this script's file access can be allowed only once de bestandstoegang van dit script kan maar één keer worden toegestaan @msg Only the person at the keyboard can allow a script's file access Alleen de persoon aan het toetsenbord kan de bestandstoegang van een script toestaan @msg A script is given at most 2,048 files: the files picked after them were left out Een script krijgt maximaal 2.048 bestanden: de bestanden die daarna zijn gekozen, zijn weggelaten diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index 6b41f2febc..6e44727fb7 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -5231,6 +5231,7 @@ liquify-list-end {0}, {1} {0} i {1} @msg `answer` for a script's file dialog must be one of: once, always, deny, stop `answer` dla okna dialogowego plików skryptu musi być jedną z wartości: once, always, deny, stop @msg choose a file or folder first, or deny najpierw wybierz plik lub folder albo odmów @msg the script file permissions could not be saved: {e} nie można zapisać uprawnień skryptów do plików: {e} +@msg the script file permissions could not be read: {e} nie można odczytać uprawnień skryptów do plików: {e} @msg this script's file access can be allowed only once na dostęp tego skryptu do plików można zezwolić tylko raz @msg Only the person at the keyboard can allow a script's file access Na dostęp skryptu do plików może zezwolić tylko osoba przy klawiaturze @msg A script is given at most 2,048 files: the files picked after them were left out Skrypt otrzymuje najwyżej 2 048 plików: pliki wybrane po nich zostały pominięte diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index 6cc30c65b5..835acc5f0c 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -6270,6 +6270,7 @@ liquify-list-end {0}, {1} {0} e {1} @msg `answer` for a script's file dialog must be one of: once, always, deny, stop `answer` para a caixa de diálogo de arquivo de um script deve ser um destes: once, always, deny, stop @msg choose a file or folder first, or deny escolha primeiro um arquivo ou uma pasta, ou negue @msg the script file permissions could not be saved: {e} não foi possível salvar as permissões de arquivos dos scripts: {e} +@msg the script file permissions could not be read: {e} não foi possível ler as permissões de arquivos dos scripts: {e} @msg this script's file access can be allowed only once o acesso a arquivos deste script só pode ser permitido uma vez @msg Only the person at the keyboard can allow a script's file access Somente a pessoa ao teclado pode permitir o acesso a arquivos de um script @msg A script is given at most 2,048 files: the files picked after them were left out Um script recebe no máximo 2.048 arquivos: os arquivos escolhidos depois deles foram deixados de fora diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index 59bc9f7d62..83e5e813fa 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -5121,6 +5121,7 @@ liquify-list-end {0}, {1} {0} и {1} @msg `answer` for a script's file dialog must be one of: once, always, deny, stop `answer` для файлового диалога скрипта должен быть одним из: once, always, deny, stop @msg choose a file or folder first, or deny сначала выберите файл или папку либо откажите @msg the script file permissions could not be saved: {e} не удалось сохранить разрешения скриптов на файлы: {e} +@msg the script file permissions could not be read: {e} не удалось прочитать разрешения скриптов на файлы: {e} @msg this script's file access can be allowed only once доступ этого скрипта к файлам можно разрешить только один раз @msg Only the person at the keyboard can allow a script's file access Разрешить скрипту доступ к файлам может только человек за клавиатурой @msg A script is given at most 2,048 files: the files picked after them were left out Скрипт получает не больше 2 048 файлов: файлы, выбранные после них, пропущены diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index d8355b2c4a..0a1f790715 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -4997,6 +4997,7 @@ liquify-list-end {0}, {1} {0} och {1} @msg `answer` for a script's file dialog must be one of: once, always, deny, stop `answer` för ett skripts fildialog måste vara ett av: once, always, deny, stop @msg choose a file or folder first, or deny välj först en fil eller mapp, eller neka @msg the script file permissions could not be saved: {e} skriptens filbehörigheter kunde inte sparas: {e} +@msg the script file permissions could not be read: {e} skriptens filbehörigheter kunde inte läsas: {e} @msg this script's file access can be allowed only once det här skriptets filåtkomst kan bara tillåtas en gång @msg Only the person at the keyboard can allow a script's file access Bara personen vid tangentbordet kan tillåta ett skripts filåtkomst @msg A script is given at most 2,048 files: the files picked after them were left out Ett skript får högst 2 048 filer: filerna som valdes efter dem utelämnades diff --git a/crates/ui-egui/src/i18n/tests.rs b/crates/ui-egui/src/i18n/tests.rs index a95d4cbf1b..b04336d7dc 100644 --- a/crates/ui-egui/src/i18n/tests.rs +++ b/crates/ui-egui/src/i18n/tests.rs @@ -2998,6 +2998,7 @@ fn script_file_messages_translate_in_every_complete_message_language() { "`answer` for a script's file dialog must be one of: once, always, deny, stop", "choose a file or folder first, or deny", "the script file permissions could not be saved: {e}", + "the script file permissions could not be read: {e}", "this script's file access can be allowed only once", "Only the person at the keyboard can allow a script's file access", ]; diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index cd74ca9166..945c03002d 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -4833,6 +4833,7 @@ liquify-list-end {0}, {1} {0} ve {1} @msg `answer` for a script's file dialog must be one of: once, always, deny, stop bir betiğin dosya iletişim kutusu için `answer` şunlardan biri olmalıdır: once, always, deny, stop @msg choose a file or folder first, or deny önce bir dosya veya klasör seçin ya da reddedin @msg the script file permissions could not be saved: {e} betiklerin dosya izinleri kaydedilemedi: {e} +@msg the script file permissions could not be read: {e} betiklerin dosya izinleri okunamadı: {e} @msg this script's file access can be allowed only once bu betiğin dosya erişimine yalnızca bir kez izin verilebilir @msg Only the person at the keyboard can allow a script's file access Bir betiğin dosya erişimine yalnızca klavye başındaki kişi izin verebilir @msg A script is given at most 2,048 files: the files picked after them were left out Bir betiğe en fazla 2.048 dosya verilir: bunlardan sonra seçilen dosyalar dışarıda bırakıldı diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index eedb12c21a..509d816012 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -5110,6 +5110,7 @@ liquify-list-end {0}, {1} {0} і {1} @msg `answer` for a script's file dialog must be one of: once, always, deny, stop `answer` для файлового діалогу скрипту має бути одним із: once, always, deny, stop @msg choose a file or folder first, or deny спершу виберіть файл або папку чи відмовте @msg the script file permissions could not be saved: {e} не вдалося зберегти дозволи скриптів на файли: {e} +@msg the script file permissions could not be read: {e} не вдалося прочитати дозволи скриптів на файли: {e} @msg this script's file access can be allowed only once доступ цього скрипту до файлів можна дозволити лише один раз @msg Only the person at the keyboard can allow a script's file access Дозволити скрипту доступ до файлів може лише людина за клавіатурою @msg A script is given at most 2,048 files: the files picked after them were left out Скрипт отримує щонайбільше 2 048 файлів: файли, вибрані після них, пропущено diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index da6d0ae64d..d7bfad3331 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -5620,6 +5620,7 @@ liquify-list-end {0}, {1} {0} và {1} @msg `answer` for a script's file dialog must be one of: once, always, deny, stop `answer` cho hộp thoại tệp của tập lệnh phải là một trong: once, always, deny, stop @msg choose a file or folder first, or deny hãy chọn một tệp hoặc thư mục trước, hoặc từ chối @msg the script file permissions could not be saved: {e} không thể lưu quyền truy cập tệp của các tập lệnh: {e} +@msg the script file permissions could not be read: {e} không thể đọc quyền truy cập tệp của các tập lệnh: {e} @msg this script's file access can be allowed only once quyền truy cập tệp của tập lệnh này chỉ có thể được cho phép một lần @msg Only the person at the keyboard can allow a script's file access Chỉ người ngồi tại bàn phím mới có thể cho phép tập lệnh truy cập tệp @msg A script is given at most 2,048 files: the files picked after them were left out Một tập lệnh nhận tối đa 2.048 tệp: các tệp được chọn sau đó đã bị bỏ qua diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index 5f66731afe..4b9233d962 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -5617,6 +5617,7 @@ liquify-list-end {0}, {1} {0}和{1} @msg `answer` for a script's file dialog must be one of: once, always, deny, stop 脚本文件对话框的 `answer` 必须是以下之一:once、always、deny、stop @msg choose a file or folder first, or deny 请先选择文件或文件夹,或拒绝 @msg the script file permissions could not be saved: {e} 无法保存脚本的文件权限:{e} +@msg the script file permissions could not be read: {e} 无法读取脚本的文件权限:{e} @msg this script's file access can be allowed only once 此脚本的文件访问只能允许一次 @msg Only the person at the keyboard can allow a script's file access 只有键盘前的人才能允许脚本访问文件 @msg A script is given at most 2,048 files: the files picked after them were left out 脚本最多获得 2,048 个文件:之后选择的文件已被略去 diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index d430105f73..5b13726f77 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -2972,6 +2972,7 @@ liquify-list-end {0}, {1} {0}和{1} @msg `answer` for a script's file dialog must be one of: once, always, deny, stop 指令碼檔案對話框的 `answer` 必須是下列之一:once、always、deny、stop @msg choose a file or folder first, or deny 請先選擇檔案或資料夾,或拒絕 @msg the script file permissions could not be saved: {e} 無法儲存指令碼的檔案權限:{e} +@msg the script file permissions could not be read: {e} 無法讀取指令碼的檔案權限:{e} @msg this script's file access can be allowed only once 此指令碼的檔案存取只能允許一次 @msg Only the person at the keyboard can allow a script's file access 只有鍵盤前的人才能允許指令碼存取檔案 @msg A script is given at most 2,048 files: the files picked after them were left out 指令碼最多取得 2,048 個檔案:之後選擇的檔案已略去 diff --git a/crates/ui-egui/src/prefs_dialog/script_access.rs b/crates/ui-egui/src/prefs_dialog/script_access.rs index 219145e60f..f1f8fa4416 100644 --- a/crates/ui-egui/src/prefs_dialog/script_access.rs +++ b/crates/ui-egui/src/prefs_dialog/script_access.rs @@ -18,6 +18,10 @@ pub(super) const ROWS: &str = "__scriptAccess"; /// The dialog field that holds the row whose Revoke button takes the keyboard focus next. const FOCUS: &str = "__scriptAccessFocus"; +/// The dialog field that holds, in English, why the grants file cannot be read or changed +/// (`script.grants`' `error`), absent when it can. +pub(super) const ERROR: &str = "__scriptAccessError"; + /// The most characters of a path a row shows. const MAX_SHOWN_PATH: usize = 1024; @@ -35,10 +39,16 @@ const WHOLE: [(&str, &str); 2] = [("script", "wholeScript"), ("path", "wholePath /// `fields`. Where the session keeps no grants, the field is removed. The grants file is the app's /// own, so it is read with no automation roots in force: each row keeps its script and path whole /// (`wholeScript` and `wholePath`) for `script.grants.revoke`, and shows them (`script` and `path`) -/// as `script.grants` names them to the request that opened the dialog ([`as_listed`]). +/// as `script.grants` names them to the request that opened the dialog ([`as_listed`]). When the +/// grants file cannot be read or changed, its error goes in the field [`ERROR`], with the rows of the +/// grants that could still be read. pub(super) fn load(app: &mut VectorcraftApp, fields: &mut Map) { + fields.remove(ERROR); match vectorcraft_engine::file_access::unconfined(|| app.session.execute("script.grants", &json!({}))) { Ok(v) if !v["file"].is_null() => { + if let Some(error) = v["error"].as_str() { + fields.insert(ERROR.into(), json!(error)); + } let mut rows = rows(&v["grants"]); for row in rows.iter_mut().filter_map(Value::as_object_mut) { for (shown, whole) in WHOLE { @@ -131,15 +141,23 @@ enum Line { } /// The section, after General › Show External Script Warning, when the dialog `d` has rows: each -/// script, its paths with their access and a Revoke button, or a line saying there are none. +/// script, its paths with their access and a Revoke button, or a line saying there are none. When +/// the grants file cannot be read or changed, its error shows first, and the line saying there are +/// none does not. pub(super) fn show(ui: &mut egui::Ui, app: &mut VectorcraftApp, d: &mut Dialog) { let Some(rows) = d.fields.get(ROWS).and_then(Value::as_array).cloned() else { return }; let t = Tokens::get(ui.ctx()); ui.add_space(8.0); ui.label(egui::RichText::new(tl!("Script File Access")).font(theme::semibold(12.5)).color(t.text_strong)); ui.add_space(2.0); + let error = d.fields.get(ERROR).and_then(Value::as_str); + if let Some(error) = error { + ui.label(egui::RichText::new(crate::i18n::msg(error)).color(t.error).size(11.5)); + } if rows.is_empty() { - ui.label(egui::RichText::new(tl!("No script has kept file access.")).color(t.text_dim).size(11.5)); + if error.is_none() { + ui.label(egui::RichText::new(tl!("No script has kept file access.")).color(t.text_dim).size(11.5)); + } return; } let mut lines = Vec::with_capacity(rows.len() * 2); diff --git a/crates/ui-egui/src/prefs_dialog/tests.rs b/crates/ui-egui/src/prefs_dialog/tests.rs index 94d710dead..10e4305b34 100644 --- a/crates/ui-egui/src/prefs_dialog/tests.rs +++ b/crates/ui-egui/src/prefs_dialog/tests.rs @@ -3211,6 +3211,32 @@ fn script_file_access_revoke_refuses_a_malformed_or_oversized_grants_file() { } } +/// Preferences opened over a grants file that cannot be read or changed (not well formed, not +/// JSON, or over 4 MiB) shows why under Script File Access instead of saying that no script has +/// kept file access, lists the grants that can still be read, and leaves the file as it was. +#[test] +fn script_file_access_shows_why_the_grants_file_cannot_be_read() { + let dir = std::env::temp_dir().join("vc-ui-prefs-grants-nowhere"); + let kept = grant(&dir.join("a.jsx"), &dir.join("out.txt"), "1", false, false); + let malformed = serde_json::to_vec(&json!({"version": 1, "grants": [kept, {"script": "x"}]})).unwrap(); + let mut oversized = br#"{"version": 1, "grants": []}"#.to_vec(); + oversized.resize((4 << 20) + 1, b' '); + for (name, held, rows) in [("malformed", malformed, 1), ("broken", b"{ not json".to_vec(), 0), ("oversized", oversized, 0)] { + let (mut a, store) = app_with_grants(&format!("grants-unread-{name}"), json!([])); + std::fs::write(&store, &held).unwrap(); + open(&mut a, Some("General")); + assert_eq!(access_rows(&a).len(), rows, "{name}"); + let fields = &a.ui.dialog.as_ref().unwrap().fields; + let error = fields.get(script_access::ERROR).and_then(Value::as_str).unwrap_or_default().to_string(); + assert!(error.starts_with("the script file permissions could not be read: "), "{name}: {error:?}"); + script_access_in_view(&mut a, &fonts_context(), &error); + let text = crate::tests_labels::painted_text(&mut a, |a, ui| show(a, ui.ctx())); + assert!(!text.contains("No script has kept file access."), "{name}: {text}"); + assert_eq!(std::fs::read(&store).unwrap(), held, "{name}: the grants file is left as it was"); + let _ = std::fs::remove_dir_all(store.parent().unwrap()); + } +} + /// A script or path with control or bidirectional formatting characters shows them as escapes, so /// it cannot break its row or draw as another name. #[test] diff --git a/docs/mcp.md b/docs/mcp.md index 1253778638..f1106d23c6 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -3047,7 +3047,7 @@ VectorCraft writes files by these rules of its own: `Script file dialogs need a person to answer them`, and takes no kept grant. In the app, a file dialog inside a built-in's callback, a getter, a conversion or a file `$.evalFile` runs throws an error. -`script.grants {}` lists the kept grants: `{grants: [{script, sha256, code, path, write, folder}], file}`, with `code` +`script.grants {}` lists the kept grants: `{grants: [{script, sha256, code, path, write, folder}], file, error?}`, with `code` the SHA-256 of each evaluated source (of its UTF-16 code units in little-endian order), `folder` true for a folder's grant, which covers everything in the folder (a file's grant covers its own path only, also when a folder later takes its place), and `file` the grants @@ -3056,8 +3056,10 @@ is given as its file name alone. `script.grants.revoke {script?, path?, all?}` r a script file, of a path, of both together, or with `all: true` every grant, and returns `{removed}`. A path is matched after its links are followed; under automation read roots, a path outside them is matched as given. While a script runs it is refused with the busy error, as the run keeps the grants it started with. A grants file that is there but -cannot be read is left as it is: `script.grants.revoke` fails, and a grant picked with Always is not kept. A script -cannot run either command. +cannot be read is left as it is: `script.grants.revoke` fails, and a grant picked with Always is not kept. For such a +file, and one that is over 4 MiB, is not a version 1 grants file, holds a grant that is not well formed or more than +4096 grants, or whose lock cannot be taken, `script.grants` gives the reason in `error` and lists the well-formed grants +it can still read. Preferences › General › Script File Access shows that error. A script cannot run either command. ```json {"name":"run_command","arguments":{"command":"script.grants.revoke","params":{"all":true}}} diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 9b0a072347..119a93b3c6 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1041,7 +1041,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - Scripts: `$.line` is the line of the running script, counting from 1, and `$.stack` is the current stack trace ([the help page](https://extendscript.docsforadobe.dev/extendscript-tools-features/dollar-object/)). VectorCraft's own rules: both count lines in the file the code is in (the script, a file it included, a file `$.evalFile` ran, or the file of an earlier run of the named engine), and `$.stack` writes each frame as `name@file:line`, outermost first; code that `eval` or `Function` compiled keeps its own line in `[eval]`, and code whose place the engine no longer keeps is at line 0 of `[unknown]`. `crates/engine/src/tests/script_include.rs`, `crates/engine/src/tests/script_engines.rs`, `crates/js/src/extension_tests.rs`. - Scripts: `File` and `Folder` ([File object](https://extendscript.docsforadobe.dev/file-system-access/file-object/), [Folder object](https://extendscript.docsforadobe.dev/file-system-access/folder-object/)) name files and folders by platform or URI path, with `name`, `fsName`, `absoluteURI`, `relativeURI`, `parent`, `Folder.current` and `encode`/`decode`, and read them: `exists`, `length`, the dates, `getFiles` with a mask or a function, and `open('r')` with `read`, `readln`, `readch`, `seek`, `tell` and `close`, decoding by byte order mark, `encoding`, UTF-8 or CP1252. VectorCraft's own rules: a script reads only in its own folder and below (and inside the automation read roots when they are set); any other path and a network or device path are refused before anything is looked up, and a link that leads out is refused as well (`false` or `null`, with `error` set); a file is read whole up to 8 MiB and a run reads up to 32 MiB; `execute` is not available. `crates/engine/src/tests/script_io.rs`. - Scripts: `File` and `Folder` write ([File object](https://extendscript.docsforadobe.dev/file-system-access/file-object/), [Folder object](https://extendscript.docsforadobe.dev/file-system-access/folder-object/)): `open('w')`, `open('e')` and `open('a')` with `write` and `writeln` by `lineFeed`, `copy`, `remove` (a folder only when empty), `rename`, `folder.create()`, the `length` and `readonly` setters, and `File.openDialog`, `File.saveDialog`, `Folder.selectDialog`, `openDlg`, `saveDlg` and `selectDlg`, with a `filter` of file types or a filter function and `multiSelect`. VectorCraft's own rules: a script writes only in `Folder.temp` (one for the run, deleted when it ends), its own `Folder.userData` next to the settings, and what a person allowed it in a file dialog, once or always; Always keeps the grant for that script file with that text by its SHA-256 and for the sources the run evaluated (`$.evalFile`, `eval`, `Function`), so a run that evaluates other code, or whose named engine holds other code, loses it first; `script.grants` lists the grants and `script.grants.revoke` removes them; the settings folder is kept out of every grant; the commands a script runs with `vc.run` read and write only in the same places and the open documents' own files; a run with nobody to ask gets `null` from the dialogs; a file is written at close or when the run ends, 8 MiB a file and 32 MiB a run, and named in `written`, also after a run that failed. `crates/engine/src/tests/script_io.rs`. - - Scripts: Preferences › General › Script File Access lists the file access kept with Always Allow This Script (`script.grants`), one row for each script and path with its widest access (read file, read and write file, or read and write folder), and its Revoke button removes every kept version of that script and path (`script.grants.revoke`), so the next run asks again. Paths show control and bidirectional characters as escapes, and a script or path outside the automation read roots in force when Preferences opens shows by its file name, as `script.grants` lists it, and Revoke still removes it; a grants file that is not well formed or is over 4 MiB makes Revoke show its error and leaves the file as it was. VectorCraft's own addition. `crates/ui-egui/src/prefs_dialog/tests.rs` (`script_file_access_*`). + - Scripts: Preferences › General › Script File Access lists the file access kept with Always Allow This Script (`script.grants`), one row for each script and path with its widest access (read file, read and write file, or read and write folder), and its Revoke button removes every kept version of that script and path (`script.grants.revoke`), so the next run asks again. Paths show control and bidirectional characters as escapes, and a script or path outside the automation read roots in force when Preferences opens shows by its file name, as `script.grants` lists it, and Revoke still removes it; a grants file that is not well formed or is over 4 MiB shows its error in the section when Preferences opens, with the grants that can still be read, makes Revoke show its error, and is left as it was. VectorCraft's own addition. `crates/ui-egui/src/prefs_dialog/tests.rs` (`script_file_access_*`). - Scripts: the `hidden` setter and `createAlias(target)` ([File object](https://extendscript.docsforadobe.dev/file-system-access/file-object/)), with setting `hidden`, `rename` and `remove` acting on an alias itself ([Using File and Folder objects](https://extendscript.docsforadobe.dev/file-system-access/using-file-and-folder-objects/)). VectorCraft's own rules: on Unix a name that starts with a dot is hidden, so setting `hidden` renames the file with one dot added or its leading dots taken off, and both names must be places the script may write; `createAlias` makes a symbolic link to the real path of a file the script may read, in a place it may write where nothing is, a link that leads nowhere included; a link is checked again each time it is used; on Windows both set `error` and change nothing. `crates/engine/src/tests/script_io.rs`. - Scripts: `#strict on` (and `//@strict on`) runs the script with the checks the [`$` object](https://extendscript.docsforadobe.dev/extendscript-tools-features/dollar-object/) help page gives for `$.strict`: an assignment to a read-only property throws a `TypeError`, and so does a new property on an object that takes none. VectorCraft's own rules: a getter-only property counts as read-only, the objects that take no new properties are the non-extensible ones (`Object.preventExtensions`, `seal`, `freeze`, and the frozen `vc` and `$` objects), the last `#strict` line of the script and its includes sets the whole run, a file `$.evalFile` runs keeps its own line's checks for its code, and the rest of ES5 strict mode stays with `'use strict'`. Without the line, runs are unchanged. `crates/engine/src/tests/script_include.rs` (`strict_on_*`, `strict_mode_in_eval_file_is_scoped`), `crates/js/src/interp_tests.rs` (`strict_writes_are_separate_from_es5_strict`). - Scripts folder: File › Scripts lists the `.js` and `.jsx` files of the `Scripts` folder next to the preferences, each named after its file without the extension, with each subfolder as a submenu, above Check Script… and Other Script… (https://helpx.adobe.com/illustrator/desktop/automate-visualize-data/automate-actions/install-and-run-scripts.html). VectorCraft's own rules: the folder is read again when the window becomes active and when the File menu opens (in the macOS menu bar, when any of its menus opens, and the new listing shows the next time the menu opens), links are not followed, and one read stops at 2,048 entries, 512 scripts, 128 subfolders, 4 levels or 250 ms. `script.listInstalled` returns the listing. `crates/engine/src/tests/script_folder.rs`, `crates/ui-egui/src/tests/scripts_menu.rs`. From cb3946fe2f041f18e86de7e5be23d8be95f6345a Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 22:23:15 -0800 Subject: [PATCH 045/151] Quick Pen: an open end on a selected segment continues its path A click on an open end of another path that lies on a segment of the selected path now goes on drawing from that end, and the pointer shows that it will. Before, the segment took the press and the click started a new path. An anchor of the selected path still comes first. --- crates/engine/src/tests/quickpen.rs | 17 +++++++++++++++++ crates/tools/src/quickpen.rs | 17 ++++++++++++++--- 2 files changed, 31 insertions(+), 3 deletions(-) diff --git a/crates/engine/src/tests/quickpen.rs b/crates/engine/src/tests/quickpen.rs index e9181b03d7..aa0b7b088b 100644 --- a/crates/engine/src/tests/quickpen.rs +++ b/crates/engine/src/tests/quickpen.rs @@ -821,6 +821,23 @@ fn a_segment_drag_moves_only_its_ends() { assert_eq!(paths(&s).len(), 1); } +/// A click on an open end of another path, in front of the selected path, that lies on a segment +/// of the selected path goes on drawing from that end. +#[test] +fn an_open_end_on_a_selected_segment_continues_its_path() { + let mut s = session(); + let id = selected_quick_pen_path(&mut s, (100.0, 300.0), json!([{"x": 300, "y": 300}])); + let r = s.execute("shape.line", &json!({"x1": 200, "y1": 200, "x2": 200, "y2": 300})).unwrap(); + let other = NodeId(r["id"].as_u64().unwrap()); + s.execute("select.set", &json!({"ids": [id.0]})).unwrap(); + click(&mut s, 200.0, 300.0); + click(&mut s, 250.0, 250.0); + let all = paths(&s); + assert_eq!(all.len(), 2, "no new path"); + let ends: Vec = all.iter().find(|(id, _)| *id == other).unwrap().1.subpaths[0].anchors.iter().map(|a| a.p).collect(); + assert_eq!(ends, [pt(200.0, 200.0), pt(200.0, 300.0), pt(250.0, 250.0)]); +} + /// Escape during a drag puts the anchor back, and the release then changes nothing. #[test] fn escape_takes_back_an_anchor_drag() { diff --git a/crates/tools/src/quickpen.rs b/crates/tools/src/quickpen.rs index 62819f793f..fa2c93709c 100644 --- a/crates/tools/src/quickpen.rs +++ b/crates/tools/src/quickpen.rs @@ -449,7 +449,10 @@ impl QuickPenTool { self.press = Some(Press { at: p, dragged: false, begun: true }); return vec![Action::Begin("Quick Pen".into()), Action::Preview(COMMAND.into(), self.params(false)), drawn()]; } - if let Some(grab) = edit::grab_at(cx, p, tol) { + // An anchor of a selected path comes first, then an open end, then a selected path's + // segment. + let grab = edit::grab_at(cx, p, tol); + if let Some(grab @ Grab::Anchor { .. }) = grab { self.edit = Some(Edit::new(cx, grab, p, shift)); return vec![]; } @@ -458,6 +461,10 @@ impl QuickPenTool { { return self.continue_path(cx, id, si, at_first); } + if let Some(grab) = grab { + self.edit = Some(Edit::new(cx, grab, p, shift)); + return vec![]; + } self.start_path(cx, p) } @@ -789,10 +796,14 @@ impl Tool for QuickPenTool { if let Some(e) = &self.edit { return if e.began { Cursor::Move } else { edit::cursor(cx, e.grab) }; } - if let Some(grab) = edit::grab_at(cx, p, tol) { + let grab = edit::grab_at(cx, p, tol); + if let Some(grab @ Grab::Anchor { .. }) = grab { return edit::cursor(cx, grab); } - if open_end_at(cx, p, tol, None).is_some() { Cursor::PenContinue } else { Cursor::Pen } + if open_end_at(cx, p, tol, None).is_some() { + return Cursor::PenContinue; + } + grab.map_or(Cursor::Pen, |grab| edit::cursor(cx, grab)) } fn options(&self) -> Value { From 2c43762b36dadf4a1bf24efff8d1a0ea19e54b67 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 23:47:18 -0800 Subject: [PATCH 046/151] Scripts: report an unreadable Startup Scripts folder at launch and attach it in the CLI At launch, when Run Startup Scripts is on and the Startup Scripts folder is there but cannot be read, or a file is where the folder should be, the status bar says the folder cannot be read. The message does not carry the folder's path, so automation replies under read roots do not show it. vectorcraft-cli attaches the same Startup Scripts folder for script.startup.run and never runs it on its own. --- apps/vectorcraft-cli/src/main.rs | 4 +++- crates/ui-egui/src/i18n/bg.tsv | 1 + crates/ui-egui/src/i18n/bs.tsv | 1 + crates/ui-egui/src/i18n/ca.tsv | 1 + crates/ui-egui/src/i18n/cs.tsv | 1 + crates/ui-egui/src/i18n/da.tsv | 1 + crates/ui-egui/src/i18n/de.tsv | 1 + crates/ui-egui/src/i18n/el.tsv | 1 + crates/ui-egui/src/i18n/es.tsv | 1 + crates/ui-egui/src/i18n/fi.tsv | 1 + crates/ui-egui/src/i18n/fr.tsv | 1 + crates/ui-egui/src/i18n/gu.tsv | 1 + crates/ui-egui/src/i18n/hi.tsv | 1 + crates/ui-egui/src/i18n/hu.tsv | 1 + crates/ui-egui/src/i18n/id.tsv | 1 + crates/ui-egui/src/i18n/it.tsv | 1 + crates/ui-egui/src/i18n/ja.tsv | 1 + crates/ui-egui/src/i18n/ka.tsv | 1 + crates/ui-egui/src/i18n/ko.tsv | 1 + crates/ui-egui/src/i18n/nl.tsv | 1 + crates/ui-egui/src/i18n/pl.tsv | 1 + crates/ui-egui/src/i18n/pt-br.tsv | 1 + crates/ui-egui/src/i18n/ru.tsv | 1 + crates/ui-egui/src/i18n/sv.tsv | 1 + crates/ui-egui/src/i18n/tr.tsv | 1 + crates/ui-egui/src/i18n/uk.tsv | 1 + crates/ui-egui/src/i18n/vi.tsv | 1 + crates/ui-egui/src/i18n/zh-hans.tsv | 1 + crates/ui-egui/src/i18n/zh-hant.tsv | 1 + crates/ui-egui/src/script_runs.rs | 9 ++++++--- crates/ui-egui/src/tests/scripts_menu.rs | 21 +++++++++++++++++++++ docs/mcp.md | 4 +++- 32 files changed, 61 insertions(+), 5 deletions(-) diff --git a/apps/vectorcraft-cli/src/main.rs b/apps/vectorcraft-cli/src/main.rs index 533074b9b5..09e898b2cf 100644 --- a/apps/vectorcraft-cli/src/main.rs +++ b/apps/vectorcraft-cli/src/main.rs @@ -238,11 +238,13 @@ fn main() -> ExitCode { /// A headless session that remembers what the user keeps between runs: the PDF presets saved, the /// ICC profiles loaded, the plug-ins installed (#2168, #2174, #2541), the custom dictionary's words (#4936) and the Color Settings (#6335), in the folders /// and files next to the preferences that the desktop app uses too, and lists the scripts of the Scripts folder there -/// (`script.listInstalled`), keeps each script's `Folder.userData` in the Script Data folder there, keeps File Info's +/// (`script.listInstalled`) and finds its Startup Scripts folder (`script.startup.run`, never run on its own), keeps each +/// script's `Folder.userData` in the Script Data folder there, keeps File Info's /// metadata templates there and starts new documents from the New Document profiles there. `VECTORCRAFT_NO_PREFS` and /// `VECTORCRAFT_CONFIG_DIR` apply as they do there. fn with_stores(mut h: Headless) -> Headless { prefs_dir::attach_scripts_dir(&mut h.session); + prefs_dir::attach_startup_scripts_dir(&mut h.session); prefs_dir::attach_script_data(&mut h.session); prefs_dir::attach_metadata_templates_dir(&mut h.session); prefs_dir::attach_new_doc_profiles(&mut h.session); diff --git a/crates/ui-egui/src/i18n/bg.tsv b/crates/ui-egui/src/i18n/bg.tsv index 8bcb952c63..038f2d5202 100644 --- a/crates/ui-egui/src/i18n/bg.tsv +++ b/crates/ui-egui/src/i18n/bg.tsv @@ -2616,6 +2616,7 @@ font-technology Variable Променливи Other Library… Друга библиотека… Some scripts were not listed Някои скриптове не са изброени The Scripts folder cannot be read Папката Scripts не може да бъде прочетена +@msg The Startup Scripts folder cannot be read Папката Startup Scripts не може да бъде прочетена Loading scripts… Зареждане на скриптовете… The Scripts folder is still being read Папката Scripts все още се чете Other Script… Друг скрипт… diff --git a/crates/ui-egui/src/i18n/bs.tsv b/crates/ui-egui/src/i18n/bs.tsv index 16936c57cf..1a58a61708 100644 --- a/crates/ui-egui/src/i18n/bs.tsv +++ b/crates/ui-egui/src/i18n/bs.tsv @@ -64,6 +64,7 @@ Check Script Provjeri skriptu Some scripts were not listed Neke skripte nisu navedene The Scripts folder cannot be read Folder Scripts se ne može pročitati +@msg The Startup Scripts folder cannot be read Folder Startup Scripts se ne može pročitati Loading scripts… Učitavanje skripti… The Scripts folder is still being read Folder Scripts se još čita Other Script… Druga skripta… diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index 9c5b633a50..3c32c8ba57 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -6441,6 +6441,7 @@ digits Malayalam Malaiàlam @msg the script is no longer in the Scripts folder l'script ja no és a la carpeta Scripts Some scripts were not listed Alguns scripts no s'han llistat The Scripts folder cannot be read No es pot llegir la carpeta Scripts +@msg The Startup Scripts folder cannot be read No es pot llegir la carpeta Startup Scripts Loading scripts… S’estan carregant els scripts… The Scripts folder is still being read Encara s’està llegint la carpeta Scripts @msg the script's run is no longer available l'execució de l'script ja no està disponible diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index 82bc2d5fb6..4ed3478543 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -5249,6 +5249,7 @@ imageTrace Outline Obrys @msg the script is no longer in the Scripts folder skript už není ve složce Scripts Some scripts were not listed Některé skripty nebyly uvedeny The Scripts folder cannot be read Složku Scripts nelze přečíst +@msg The Startup Scripts folder cannot be read Složku Startup Scripts nelze přečíst Loading scripts… Načítání skriptů… The Scripts folder is still being read Složka Scripts se stále načítá @msg the script's run is no longer available běh skriptu již není k dispozici diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index 54f430fe98..6349480e27 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -820,6 +820,7 @@ liquify-list-end {0}, {1} {0} og {1} Check Script Kontrollér script Some scripts were not listed Nogle scripter blev ikke vist The Scripts folder cannot be read Mappen Scripts kan ikke læses +@msg The Startup Scripts folder cannot be read Mappen Startup Scripts kan ikke læses Loading scripts… Indlæser scripter… The Scripts folder is still being read Mappen Scripts læses stadig Other Script… Andet script… diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index 7786ab6c1f..0b51de1ba1 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -4834,6 +4834,7 @@ theme Appearance Erscheinungsbild @msg the script is no longer in the Scripts folder das Skript befindet sich nicht mehr im Ordner „Scripts“ Some scripts were not listed Einige Skripte wurden nicht aufgeführt The Scripts folder cannot be read Der Ordner „Scripts“ kann nicht gelesen werden +@msg The Startup Scripts folder cannot be read Der Ordner „Startup Scripts“ kann nicht gelesen werden Loading scripts… Skripte werden geladen… The Scripts folder is still being read Der Ordner „Scripts“ wird noch gelesen @msg the script's run is no longer available der Lauf des Skripts ist nicht mehr verfügbar diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index 4dc97a67b5..53de3bac32 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -2637,6 +2637,7 @@ axis Both Και τα δύο @msg the script is no longer in the Scripts folder το σενάριο δεν βρίσκεται πλέον στον φάκελο Scripts Some scripts were not listed Ορισμένα σενάρια δεν εμφανίζονται στη λίστα The Scripts folder cannot be read Δεν είναι δυνατή η ανάγνωση του φακέλου Scripts +@msg The Startup Scripts folder cannot be read Δεν είναι δυνατή η ανάγνωση του φακέλου Startup Scripts Loading scripts… Φόρτωση σεναρίων… The Scripts folder is still being read Ο φάκελος Scripts διαβάζεται ακόμα @msg the script's run is no longer available η εκτέλεση του σεναρίου δεν είναι πλέον διαθέσιμη diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index 5a3b001197..13c451f657 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -4913,6 +4913,7 @@ axis Both Ambos @msg the script is no longer in the Scripts folder el script ya no está en la carpeta Scripts Some scripts were not listed Algunos scripts no se han incluido en la lista The Scripts folder cannot be read No se puede leer la carpeta Scripts +@msg The Startup Scripts folder cannot be read No se puede leer la carpeta Startup Scripts Loading scripts… Cargando scripts… The Scripts folder is still being read Aún se está leyendo la carpeta Scripts @msg the script's run is no longer available la ejecución del script ya no está disponible diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index b6aec2d644..9f9a2a66ee 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -5154,6 +5154,7 @@ imageTrace Outline Ääriviiva @msg the script is no longer in the Scripts folder komentosarja ei ole enää Scripts-kansiossa Some scripts were not listed Kaikkia komentosarjoja ei ole lueteltu The Scripts folder cannot be read Scripts-kansiota ei voi lukea +@msg The Startup Scripts folder cannot be read Startup Scripts -kansiota ei voi lukea Loading scripts… Ladataan komentosarjoja… The Scripts folder is still being read Scripts-kansiota luetaan vielä @msg the script's run is no longer available komentosarjan suoritus ei ole enää käytettävissä diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index e0bdcf7625..bec8831a3a 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -4895,6 +4895,7 @@ axis Both Les deux @msg the script is no longer in the Scripts folder le script ne se trouve plus dans le dossier Scripts Some scripts were not listed Certains scripts ne sont pas répertoriés The Scripts folder cannot be read Impossible de lire le dossier Scripts +@msg The Startup Scripts folder cannot be read Impossible de lire le dossier Startup Scripts Loading scripts… Chargement des scripts… The Scripts folder is still being read Le dossier Scripts est encore en cours de lecture @msg the script's run is no longer available l’exécution du script n’est plus disponible diff --git a/crates/ui-egui/src/i18n/gu.tsv b/crates/ui-egui/src/i18n/gu.tsv index b72a77a4d6..f735c1fd95 100644 --- a/crates/ui-egui/src/i18n/gu.tsv +++ b/crates/ui-egui/src/i18n/gu.tsv @@ -4372,6 +4372,7 @@ arrowhead Feather પીંછું Thai થાઈ The Print Tiling tool placed the pages. પ્રિન્ટ ટાઇલિંગ ટૂલે પૃષ્ઠો ગોઠવ્યાં. The Scripts folder cannot be read સ્ક્રિપ્ટ્સ ફોલ્ડર વાંચી શકાતું નથી +@msg The Startup Scripts folder cannot be read Startup Scripts ફોલ્ડર વાંચી શકાતું નથી Loading scripts… સ્ક્રિપ્ટ લોડ થઈ રહી છે… The Scripts folder is still being read સ્ક્રિપ્ટ્સ ફોલ્ડર હજી વંચાઈ રહ્યું છે The VECTORCRAFT_TITLEBAR environment variable chooses the title bar while it is set. જ્યારે VECTORCRAFT_TITLEBAR એન્વાયર્નમેન્ટ વેરિએબલ સેટ હોય ત્યારે તે ટાઇટલ બાર પસંદ કરે છે. diff --git a/crates/ui-egui/src/i18n/hi.tsv b/crates/ui-egui/src/i18n/hi.tsv index f2cb9a0afe..91872f2807 100644 --- a/crates/ui-egui/src/i18n/hi.tsv +++ b/crates/ui-egui/src/i18n/hi.tsv @@ -7587,6 +7587,7 @@ arrowhead Feather पंख @msg the script is no longer in the Scripts folder स्क्रिप्ट अब Scripts फ़ोल्डर में नहीं है Some scripts were not listed कुछ स्क्रिप्ट सूचीबद्ध नहीं की गईं The Scripts folder cannot be read Scripts फ़ोल्डर पढ़ा नहीं जा सकता +@msg The Startup Scripts folder cannot be read Startup Scripts फ़ोल्डर पढ़ा नहीं जा सकता Loading scripts… स्क्रिप्ट लोड हो रही हैं… The Scripts folder is still being read Scripts फ़ोल्डर अभी भी पढ़ा जा रहा है @msg the script's run is no longer available स्क्रिप्ट का रन अब उपलब्ध नहीं है diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index aa97447796..4cdebb6b6c 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -5766,6 +5766,7 @@ imageTrace Outline Körvonal @msg the script is no longer in the Scripts folder a parancsfájl már nincs a Scripts mappában Some scripts were not listed Néhány szkript nem szerepel a listában The Scripts folder cannot be read A Scripts mappa nem olvasható +@msg The Startup Scripts folder cannot be read A Startup Scripts mappa nem olvasható Loading scripts… Szkriptek betöltése… The Scripts folder is still being read A Scripts mappa olvasása még tart @msg the script's run is no longer available a parancsfájl futása már nem érhető el diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index 21908fda55..56c282c700 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -695,6 +695,7 @@ Check Script Periksa skrip Some scripts were not listed Beberapa skrip tidak dicantumkan The Scripts folder cannot be read Folder Scripts tidak dapat dibaca +@msg The Startup Scripts folder cannot be read Folder Startup Scripts tidak dapat dibaca Loading scripts… Memuat skrip… The Scripts folder is still being read Folder Scripts masih dibaca Other Script… Skrip lain… diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index d57067bbdc..30d3c17b9e 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -4972,6 +4972,7 @@ axis Both Entrambi @msg the script is no longer in the Scripts folder lo script non è più nella cartella Scripts Some scripts were not listed Alcuni script non sono stati elencati The Scripts folder cannot be read Impossibile leggere la cartella Scripts +@msg The Startup Scripts folder cannot be read Impossibile leggere la cartella Startup Scripts Loading scripts… Caricamento degli script… The Scripts folder is still being read La cartella Scripts è ancora in lettura @msg the script's run is no longer available l'esecuzione dello script non è più disponibile diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index 76f1a6404b..1d027fe166 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -5798,6 +5798,7 @@ variable-list-end {0}, {1} {0}、{1} @msg the script is no longer in the Scripts folder スクリプトは Scripts フォルダーにもうありません Some scripts were not listed 一部のスクリプトは一覧に表示されていません The Scripts folder cannot be read Scripts フォルダーを読み込めません +@msg The Startup Scripts folder cannot be read Startup Scripts フォルダーを読み込めません Loading scripts… スクリプトを読み込み中… The Scripts folder is still being read Scripts フォルダーをまだ読み込んでいます @msg the script's run is no longer available スクリプトの実行は利用できなくなりました diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index 7cb1972a56..dcaefd804f 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -8467,6 +8467,7 @@ imageTrace Outline კონტური @msg the script is no longer in the Scripts folder სკრიპტი აღარ არის Scripts საქაღალდეში Some scripts were not listed ზოგიერთი სკრიპტი არ არის ჩამოთვლილი The Scripts folder cannot be read Scripts საქაღალდის წაკითხვა შეუძლებელია +@msg The Startup Scripts folder cannot be read Startup Scripts საქაღალდის წაკითხვა შეუძლებელია Loading scripts… სკრიპტების ჩატვირთვა… The Scripts folder is still being read Scripts საქაღალდე ჯერ კიდევ იკითხება @msg the script's run is no longer available სკრიპტის გაშვება აღარ არის ხელმისაწვდომი diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index f1087286ff..f3194761a7 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -5727,6 +5727,7 @@ variable-list-end {0}, {1} {0} 및 {1} @msg the script is no longer in the Scripts folder 스크립트가 더 이상 Scripts 폴더에 없습니다 Some scripts were not listed 일부 스크립트가 나열되지 않았습니다 The Scripts folder cannot be read Scripts 폴더를 읽을 수 없습니다 +@msg The Startup Scripts folder cannot be read Startup Scripts 폴더를 읽을 수 없습니다 Loading scripts… 스크립트 불러오는 중… The Scripts folder is still being read Scripts 폴더를 아직 읽는 중입니다 @msg the script's run is no longer available 스크립트 실행을 더 이상 사용할 수 없습니다 diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index 0860fc50c7..095b74c876 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -665,6 +665,7 @@ liquify-list-end {0}, {1} {0} en {1} Check Script Script controleren Some scripts were not listed Sommige scripts zijn niet weergegeven The Scripts folder cannot be read De map Scripts kan niet worden gelezen +@msg The Startup Scripts folder cannot be read De map Startup Scripts kan niet worden gelezen Loading scripts… Scripts laden… The Scripts folder is still being read De map Scripts wordt nog gelezen Other Script… Ander script… diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index 3907186f99..90c5f96f7a 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -5077,6 +5077,7 @@ imageTrace Outline Kontur @msg the script is no longer in the Scripts folder skryptu nie ma już w folderze Scripts Some scripts were not listed Niektóre skrypty nie zostały wyświetlone The Scripts folder cannot be read Nie można odczytać folderu Scripts +@msg The Startup Scripts folder cannot be read Nie można odczytać folderu Startup Scripts Loading scripts… Wczytywanie skryptów… The Scripts folder is still being read Folder Scripts jest nadal odczytywany @msg the script's run is no longer available uruchomienie skryptu nie jest już dostępne diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index 92faaa025b..8fc5caf929 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -6116,6 +6116,7 @@ variable-list-end {0}, {1} {0} e {1} @msg the script is no longer in the Scripts folder o script não está mais na pasta Scripts Some scripts were not listed Alguns scripts não foram listados The Scripts folder cannot be read Não é possível ler a pasta Scripts +@msg The Startup Scripts folder cannot be read Não é possível ler a pasta Startup Scripts Loading scripts… Carregando scripts… The Scripts folder is still being read A pasta Scripts ainda está sendo lida @msg the script's run is no longer available a execução do script não está mais disponível diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index cde0c8d12a..28e8d37183 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -4948,6 +4948,7 @@ axis Both Оба @msg the script is no longer in the Scripts folder скрипт больше не находится в папке Scripts Some scripts were not listed Некоторые сценарии не показаны The Scripts folder cannot be read Не удалось прочитать папку Scripts +@msg The Startup Scripts folder cannot be read Не удалось прочитать папку Startup Scripts Loading scripts… Загрузка сценариев… The Scripts folder is still being read Папка Scripts ещё читается @msg the script's run is no longer available выполнение скрипта больше недоступно diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index 90bedf9d78..9f9f6601b1 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -4810,6 +4810,7 @@ axis Both Båda @msg the script is no longer in the Scripts folder skriptet finns inte längre i mappen Scripts Some scripts were not listed Vissa skript visas inte i listan The Scripts folder cannot be read Mappen Scripts kan inte läsas +@msg The Startup Scripts folder cannot be read Mappen Startup Scripts kan inte läsas Loading scripts… Läser in skript… The Scripts folder is still being read Mappen Scripts läses fortfarande @msg the script's run is no longer available skriptets körning är inte längre tillgänglig diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index 08940138fc..0388a17783 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -4670,6 +4670,7 @@ axis Both Her İkisi @msg the script is no longer in the Scripts folder betik artık Scripts klasöründe değil Some scripts were not listed Bazı komut dosyaları listelenmedi The Scripts folder cannot be read Scripts klasörü okunamıyor +@msg The Startup Scripts folder cannot be read Startup Scripts klasörü okunamıyor Loading scripts… Betikler yükleniyor… The Scripts folder is still being read Scripts klasörü hâlâ okunuyor @msg the script's run is no longer available betiğin çalıştırması artık kullanılamıyor diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index d3eff0fced..60f7356d36 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -4956,6 +4956,7 @@ axis Both Обидві @msg the script is no longer in the Scripts folder скрипт більше не міститься в папці Scripts Some scripts were not listed Деякі сценарії не показано The Scripts folder cannot be read Не вдалося прочитати папку Scripts +@msg The Startup Scripts folder cannot be read Не вдалося прочитати папку Startup Scripts Loading scripts… Завантаження сценаріїв… The Scripts folder is still being read Папка Scripts ще читається @msg the script's run is no longer available виконання скрипта більше не доступне diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index 749c0ff9de..d1cd5382c6 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -5434,6 +5434,7 @@ theme Appearance Giao diện @msg the script is no longer in the Scripts folder tập lệnh không còn trong thư mục Scripts Some scripts were not listed Một số tập lệnh không được liệt kê The Scripts folder cannot be read Không thể đọc thư mục Scripts +@msg The Startup Scripts folder cannot be read Không thể đọc thư mục Startup Scripts Loading scripts… Đang tải tập lệnh… The Scripts folder is still being read Thư mục Scripts vẫn đang được đọc @msg the script's run is no longer available lần chạy tập lệnh không còn khả dụng diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index 9658c0d9e6..b9db272073 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -5463,6 +5463,7 @@ imageTrace Outline 轮廓 @msg the script is no longer in the Scripts folder 脚本已不在 Scripts 文件夹中 Some scripts were not listed 部分脚本未列出 The Scripts folder cannot be read 无法读取 Scripts 文件夹 +@msg The Startup Scripts folder cannot be read 无法读取 Startup Scripts 文件夹 Loading scripts… 正在载入脚本… The Scripts folder is still being read 仍在读取 Scripts 文件夹 @msg the script's run is no longer available 脚本运行已不可用 diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index a2410f6810..0b4184b239 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -2808,6 +2808,7 @@ file-filter Templates 範本 @msg the script is no longer in the Scripts folder 指令碼已不在 Scripts 資料夾中 Some scripts were not listed 部分指令碼未列出 The Scripts folder cannot be read 無法讀取 Scripts 資料夾 +@msg The Startup Scripts folder cannot be read 無法讀取 Startup Scripts 資料夾 Loading scripts… 正在載入指令碼… The Scripts folder is still being read 仍在讀取 Scripts 資料夾 @msg the script's run is no longer available 指令碼執行已無法使用 diff --git a/crates/ui-egui/src/script_runs.rs b/crates/ui-egui/src/script_runs.rs index ab125bf44f..907bbdb9bc 100644 --- a/crates/ui-egui/src/script_runs.rs +++ b/crates/ui-egui/src/script_runs.rs @@ -91,13 +91,16 @@ pub(crate) fn run_chosen(app: &mut VectorcraftApp, params: Value) -> Result app.status("The Startup Scripts folder cannot be read"), + Ok(_) => {} + Err(e) => app.status(e), } } diff --git a/crates/ui-egui/src/tests/scripts_menu.rs b/crates/ui-egui/src/tests/scripts_menu.rs index f7fb97f11d..c1f418e62b 100644 --- a/crates/ui-egui/src/tests/scripts_menu.rs +++ b/crates/ui-egui/src/tests/scripts_menu.rs @@ -600,6 +600,27 @@ fn with_run_startup_scripts_on_other_script_and_the_launch_run_the_startup_scrip let _ = std::fs::remove_dir_all(dir); } +#[test] +fn a_startup_scripts_folder_that_cannot_be_read_shows_in_the_status_bar_at_launch_and_a_missing_one_does_not() { + let dir = folder("startup-unreadable"); + let mut app = app(&dir); + app.run("prefs.set", json!({"key": "runStartupScripts", "value": true})).unwrap(); + let startup = dir.join("Startup Scripts"); + app.session.attach_startup_scripts_dir(startup.clone()); + app.status("before"); + script_runs::run_at_launch(&mut app); + assert_eq!(app.ui.status, "before", "a missing folder runs nothing and says nothing"); + // A file where the folder should be cannot be listed. + std::fs::write(&startup, "not a folder").unwrap(); + script_runs::run_at_launch(&mut app); + assert!(!app.session.script_running()); + // The message names the folder without its path, which automation replies would show. + assert_eq!(app.ui.status, "The Startup Scripts folder cannot be read"); + let de = crate::i18n::Lang::from_code("de").unwrap(); + assert_eq!(crate::i18n::message(de, &app.ui.status), "Der Ordner „Startup Scripts“ kann nicht gelesen werden"); + let _ = std::fs::remove_dir_all(dir); +} + #[test] fn a_first_read_that_ends_without_a_listing_says_the_folder_cannot_be_read_and_the_next_read_tries_again() { let dir = folder("lost"); diff --git a/docs/mcp.md b/docs/mcp.md index 56a8b782be..6f81dbb3f7 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -3174,7 +3174,8 @@ The rest of this section is VectorCraft's own rules: - Only the folder's own `.jsx` files run, never its subfolders. Links, names that start with a dot, files Windows marks hidden or system, names longer than 255 bytes and other file types are left out. A listing stops at 2,048 folder - entries, 512 scripts or 250 ms. A folder that is missing runs nothing. + entries, 512 scripts or 250 ms. A folder that is missing runs nothing. At launch, when the folder is there and cannot + be read, or a file is where the folder should be, the status bar says that the folder cannot be read. - The scripts run one at a time, sorted by name without regard to case, then by name. Each runs as `script.run` runs a file, with the same limits, and each that changes a document adds its own Run Script undo step. The chosen script runs after the last of them. @@ -3187,6 +3188,7 @@ The rest of this section is VectorCraft's own rules: - Running the startup scripts is itself a `script.*` command, which a script cannot run, so a startup script cannot start another round of them. `script.run` called from automation runs alone. - The web build has no Startup Scripts folder, and neither has a run with `VECTORCRAFT_NO_PREFS` set. + `vectorcraft-cli` uses the same folder and runs it only through `script.startup.run`. `script.startup.run {reason: launch|menu, then?, maxFuel?}` runs the folder now. `then` holds `script.run`'s parameters for a script that runs after the startup scripts; `maxFuel` limits each startup script's instructions From 8d12b37da2401a55037f8e37379be2a0c6daf91b Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 22 Nov 2026 00:09:15 -0800 Subject: [PATCH 047/151] JavaScript: Symbol and the iterators of arrays, strings and arguments in ES2015 realms With Options::es2015 set, a vectorcraft-js realm has Symbol (ECMA-262 11th edition, section 19.4): Symbol(description), which new refuses, the description getter, toString, valueOf, and Symbol.for and Symbol.keyFor over a registry that lasts as long as the realm. typeof gives "symbol". Symbols are property keys: Object.getOwnPropertySymbols lists them in the order they were added, defineProperty, getOwnPropertyDescriptor, freeze, seal, in, delete and hasOwnProperty take them, and for-in, Object.keys, getOwnPropertyNames and JSON.stringify leave them out. String(symbol) and symbol.toString() give Symbol(description); any other conversion of a Symbol to a string or a number throws a TypeError. Symbol.iterator, asyncIterator, hasInstance, toPrimitive and toStringTag are defined. Conversion to a primitive calls @@toPrimitive, instanceof calls @@hasInstance, and Object.prototype.toString writes a string @@toStringTag. Array.prototype.values (also @@iterator), keys and entries, String.prototype[@@iterator] (by code point) and every arguments object's @@iterator return iterators with next(). An Array Iterator's next keeps its object reachable while a length getter or valueOf runs script. Each iterator step takes fuel, and each Symbol and registry entry counts against the heap limit. An error about a Symbol-keyed property names the Symbol by at most 256 units of its description, built only when the error is thrown. String(symbol), symbol.toString() and the [object tag] of Object.prototype.toString charge their copies to the heap and fuel first. Realms without the option, including the one the app runs scripts in, are unchanged. for-of, spread and destructuring are not part of this change. cargo xtask test262 runs the suite's Symbol, ArrayIteratorPrototype, StringIteratorPrototype, getOwnPropertySymbols, Array.prototype values/keys/entries/Symbol.iterator and String.prototype[Symbol.iterator] tests in such a realm: 164 of 216 runs pass (6 before). The 52 others expect a configurable function length and a function name property. --- crates/js/src/builtins.rs | 28 +- crates/js/src/builtins/extensions.rs | 8 +- crates/js/src/builtins/iterator.rs | 224 +++++++++++ crates/js/src/builtins/json.rs | 6 +- crates/js/src/builtins/object.rs | 35 +- crates/js/src/builtins/symbol.rs | 161 ++++++++ crates/js/src/heap.rs | 47 ++- crates/js/src/host.rs | 1 + crates/js/src/interp.rs | 126 ++++-- crates/js/src/lib.rs | 20 +- crates/js/src/realm.rs | 4 +- crates/js/src/string_builtins.rs | 2 + crates/js/src/symbol.rs | 581 +++++++++++++++++++++++++++ crates/js/src/symbol_tests.rs | 230 +++++++++++ crates/js/src/value.rs | 29 +- crates/js/tests/test262.rs | 116 +++++- docs/mcp.md | 4 + docs/target-app-parity.md | 1 + 18 files changed, 1557 insertions(+), 66 deletions(-) create mode 100644 crates/js/src/builtins/iterator.rs create mode 100644 crates/js/src/builtins/symbol.rs create mode 100644 crates/js/src/symbol.rs create mode 100644 crates/js/src/symbol_tests.rs diff --git a/crates/js/src/builtins.rs b/crates/js/src/builtins.rs index 380d161ecf..b8c21bbc64 100644 --- a/crates/js/src/builtins.rs +++ b/crates/js/src/builtins.rs @@ -3,7 +3,8 @@ //! `Array`, the error constructors, `Math`, `JSON`, the global functions and constants, Annex //! B's `escape` and `unescape`, and the prototypes primitive values look properties up on, with //! `Boolean.prototype`'s `toString` and `valueOf`. `String`, `Number`, `RegExp` and `Date` are in -//! their own modules. +//! their own modules. A realm with [`crate::Options::es2015`] also has `Symbol` (in `symbol`) and +//! the iterators of arrays, strings and `arguments` objects (in `iterator`). //! //! Every loop in a built-in takes a unit of fuel for each step, and every string, array, object //! or property it makes is checked against the heap limit before it is made, so no built-in can @@ -12,9 +13,11 @@ mod array; pub(crate) mod extensions; mod global; +pub(crate) mod iterator; mod json; mod math; mod object; +mod symbol; use std::rc::Rc; @@ -142,6 +145,10 @@ fn try_install(interp: &mut Interp) -> JsResult<()> { crate::number_builtins::install(interp)?; crate::regexp_builtins::install(interp)?; crate::date_builtins::install(interp)?; + if interp.options.es2015 { + symbol::install(interp, object)?; + iterator::install(interp)?; + } if interp.options.e4x { crate::xml_builtins::install(interp)?; } @@ -370,7 +377,9 @@ fn object_ctor(interp: &mut Interp, _: Value, args: &[Value], _: bool) -> JsResu interp.to_object(&v).map(Value::Object) } -/// `Object.prototype.toString` (section 15.2.4.2). +/// `Object.prototype.toString` (section 15.2.4.2). In a realm with [`crate::Options::es2015`], a +/// string `@@toStringTag` takes the place of the class name (ECMA-262 11th edition, section +/// 19.1.3.6). fn object_to_string(interp: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult { // With `$.localize` on, a localization object gives its text for the current locale. if interp.localization.enabled() @@ -384,6 +393,13 @@ fn object_to_string(interp: &mut Interp, this: Value, _: &[Value], _: bool) -> J Value::Null => "Null", _ => { let o = interp.to_object(&this)?; + // The tag's getter can run script that collects, and the object of a primitive is + // reachable from nowhere else. + let tag = interp.rooted(&[Value::Object(o)], |i| i.string_tag_of(o))?; + if let Some(tag) = tag { + let roots = [Value::String(tag.clone())]; + return interp.rooted(&roots, |i| i.wrap_str("[object ", Some(&tag), "]")); + } interp.heap.object(o).map_or("Object", |o| o.class.name()) } }; @@ -431,9 +447,9 @@ fn object_value_of(interp: &mut Interp, this: Value, _: &[Value], _: bool) -> Js } fn has_own_property(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { - let k = interp.to_key(&arg(args, 0))?; + let k = interp.to_prop_key(&arg(args, 0))?; let o = interp.to_object(&this)?; - Ok(Value::Bool(interp.get_own_property(o, &k)?.is_some())) + Ok(Value::Bool(interp.get_own_pk(o, &k)?.is_some())) } fn is_prototype_of(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { @@ -450,9 +466,9 @@ fn is_prototype_of(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> } fn property_is_enumerable(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { - let k = interp.to_key(&arg(args, 0))?; + let k = interp.to_prop_key(&arg(args, 0))?; let o = interp.to_object(&this)?; - Ok(Value::Bool(interp.get_own_property(o, &k)?.is_some_and(|p| p.enumerable()))) + Ok(Value::Bool(interp.get_own_pk(o, &k)?.is_some_and(|p| p.enumerable()))) } // ---- Function ---- diff --git a/crates/js/src/builtins/extensions.rs b/crates/js/src/builtins/extensions.rs index 94ee226d57..b32fecdcb5 100644 --- a/crates/js/src/builtins/extensions.rs +++ b/crates/js/src/builtins/extensions.rs @@ -235,6 +235,7 @@ impl Source { } Value::String(s) => self.quoted(interp, &s.flat()), Value::Object(id) => self.object(interp, *id), + Value::Symbol(_) => Err(interp.type_error("toSource: a Symbol cannot be written as source")), } } @@ -280,13 +281,18 @@ impl Source { // only, so an array with other properties, an object with another prototype and a property // that is not enumerable are refused. let enumerable = o.props.iter().all(|(_, p)| p.enumerable()); + let has_symbols = o.syms.as_ref().is_some_and(|m| m.len() > 0); let shape = match &o.class { Class::Array { length, .. } - if o.proto == Some(array_proto) && enumerable && o.props.iter().all(|(k, _)| array_index(k).is_some_and(|i| i < *length)) => + if o.proto == Some(array_proto) + && enumerable + && !has_symbols + && o.props.iter().all(|(k, _)| array_index(k).is_some_and(|i| i < *length)) => { Some(Err(*length)) } Class::Array { .. } => return Err(interp.type_error(NOT_PLAIN_ARRAY)), + Class::Ordinary if has_symbols => return Err(interp.type_error("toSource: an object with a Symbol property cannot be written as source")), Class::Ordinary if o.proto == Some(object_proto) && enumerable => { Some(Ok(o.props.iter().map(|(k, p)| (k.clone(), p.clone())).collect::>())) } diff --git a/crates/js/src/builtins/iterator.rs b/crates/js/src/builtins/iterator.rs new file mode 100644 index 0000000000..317b66ecc2 --- /dev/null +++ b/crates/js/src/builtins/iterator.rs @@ -0,0 +1,224 @@ +//! The iterators of arrays, strings and `arguments` objects (ECMA-262 11th edition, +//! ): `%IteratorPrototype%` (section 25.1.2), +//! `%ArrayIteratorPrototype%` with `Array.prototype.values`, `keys`, `entries` and `@@iterator` +//! (sections 22.1.3 and 22.1.5), `%StringIteratorPrototype%` with `String.prototype[@@iterator]` +//! (sections 21.1.3.29 and 21.1.5), which steps by code point, and the `@@iterator` of every +//! `arguments` object (section 9.4.4). Installed in a realm with [`crate::Options::es2015`] only. +//! +//! An iterator's `next` takes a unit of fuel for each step. An Array Iterator reads its object's +//! `length` at every step, so elements added while it runs are visited, and it lets go of the +//! object once it is done. + +use super::{create_at, data, native, new_array, new_string}; +use crate::heap::{CONFIGURABLE, Class, HIDDEN, OBJECT_BYTES, OPEN, ObjId, Object, PROP_BYTES, Prop, key}; +use crate::interp::{Interp, JsResult}; +use crate::value::{Str, Value, number_to_str}; + +/// What an Array Iterator gives at each step (section 22.1.5.1). +#[derive(Clone, Copy, PartialEq, Eq)] +pub(crate) enum ArrayKind { + Keys, + Values, + Entries, +} + +/// An iterator's state. The object or string is `None` once the iterator is done. +#[derive(Clone)] +pub(crate) enum IterState { + /// [[IteratedObject]], [[ArrayIteratorNextIndex]] and [[ArrayIterationKind]]. + Array { target: Option, next: f64, kind: ArrayKind }, + /// [[IteratedString]], flat, and [[StringIteratorNextIndex]] in code units. + String { text: Option, pos: usize }, +} + +pub(super) fn install(interp: &mut Interp) -> JsResult<()> { + let Some(wk) = interp.symbols.well_known.as_ref() else { return Ok(()) }; + let (iterator, to_string_tag) = (wk.iterator.clone(), wk.to_string_tag.clone()); + let Some(mut objects) = interp.symbols.objects else { return Ok(()) }; + + let object_proto = interp.intrinsics.object_proto; + let iterator_proto = interp.heap.alloc_object(Object::new(Class::Ordinary, Some(object_proto))); + super::symbol::sym_method(interp, iterator_proto, iterator.clone(), "[Symbol.iterator]", return_this, 0, HIDDEN)?; + + let array_iterator_proto = interp.heap.alloc_object(Object::new(Class::Ordinary, Some(iterator_proto))); + super::method(interp, array_iterator_proto, "next", array_iterator_next, 0)?; + interp.define_sym(array_iterator_proto, to_string_tag.clone(), Prop::Data { value: Value::str("Array Iterator"), flags: CONFIGURABLE })?; + + let string_iterator_proto = interp.heap.alloc_object(Object::new(Class::Ordinary, Some(iterator_proto))); + super::method(interp, string_iterator_proto, "next", string_iterator_next, 0)?; + interp.define_sym(string_iterator_proto, to_string_tag, Prop::Data { value: Value::str("String Iterator"), flags: CONFIGURABLE })?; + + let array_proto = interp.intrinsics.array_proto; + let values = native(interp, "values", array_values, 0, crate::heap::NativeKind::Plain, false)?; + data(interp, array_proto, "values", Value::Object(values), HIDDEN)?; + interp.define_sym(array_proto, iterator.clone(), Prop::Data { value: Value::Object(values), flags: HIDDEN })?; + super::method(interp, array_proto, "keys", array_keys, 0)?; + super::method(interp, array_proto, "entries", array_entries, 0)?; + + let string_proto = interp.intrinsics.string_proto; + super::symbol::sym_method(interp, string_proto, iterator, "[Symbol.iterator]", string_iterator, 0, HIDDEN)?; + + objects.array_iterator_proto = array_iterator_proto; + objects.string_iterator_proto = string_iterator_proto; + objects.array_values = values; + interp.symbols.objects = Some(objects); + Ok(()) +} + +/// Gives a new `arguments` object its `@@iterator`, `%ArrayProto_values%` (section 9.4.4.6, +/// step 20, and section 9.4.4.7, step 7), in a realm that has it. +pub(crate) fn define_arguments_iterator(interp: &mut Interp, a: ObjId) -> JsResult<()> { + let (Some(objects), Some(sym)) = (interp.symbols.objects, interp.well_known(|w| &w.iterator)) else { return Ok(()) }; + interp.define_sym(a, sym, Prop::Data { value: Value::Object(objects.array_values), flags: HIDDEN }) +} + +/// `%IteratorPrototype%[@@iterator]()` (section 25.1.2.1): the iterator itself. +fn return_this(_: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult { + Ok(this) +} + +/// CreateIterResultObject (section 7.4.7): `{ value, done }`. +fn iter_result(interp: &mut Interp, value: Value, done: bool) -> JsResult { + interp.rooted(std::slice::from_ref(&value), |i| i.reserve_heap(OBJECT_BYTES + 2 * PROP_BYTES))?; + let proto = interp.intrinsics.object_proto; + let o = interp.heap.alloc_object(Object::new(Class::Ordinary, Some(proto))); + interp.define(o, key("value"), Prop::Data { value, flags: OPEN })?; + interp.define(o, key("done"), Prop::Data { value: Value::Bool(done), flags: OPEN })?; + Ok(Value::Object(o)) +} + +/// A new iterator object with `state`, its target kept reachable while it is made. +fn new_iterator(interp: &mut Interp, proto: ObjId, state: IterState, root: Value) -> JsResult { + interp.rooted(&[root], |i| i.reserve_heap(OBJECT_BYTES))?; + Ok(Value::Object(interp.heap.alloc_object(Object::new(Class::Iterator(Box::new(state)), Some(proto))))) +} + +/// CreateArrayIterator (section 22.1.5.1) for `ToObject(this)`. +fn create_array_iterator(interp: &mut Interp, this: &Value, kind: ArrayKind) -> JsResult { + let o = interp.to_object(this)?; + let Some(proto) = interp.symbols.objects.map(|o| o.array_iterator_proto) else { return Ok(Value::Undefined) }; + new_iterator(interp, proto, IterState::Array { target: Some(o), next: 0.0, kind }, Value::Object(o)) +} + +/// `Array.prototype.values()` (section 22.1.3.32), which is also `Array.prototype[@@iterator]`. +fn array_values(interp: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult { + create_array_iterator(interp, &this, ArrayKind::Values) +} + +/// `Array.prototype.keys()` (section 22.1.3.16). +fn array_keys(interp: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult { + create_array_iterator(interp, &this, ArrayKind::Keys) +} + +/// `Array.prototype.entries()` (section 22.1.3.4). +fn array_entries(interp: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult { + create_array_iterator(interp, &this, ArrayKind::Entries) +} + +/// `String.prototype[@@iterator]()` (section 21.1.3.29). +fn string_iterator(interp: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult { + if this.is_nullish() { + return Err(interp.type_error("String.prototype[Symbol.iterator] was called on null or undefined")); + } + let s = interp.to_str(&this)?; + let flat = Str::from_rc(crate::string_builtins::flat_charged(interp, &s)?); + let Some(proto) = interp.symbols.objects.map(|o| o.string_iterator_proto) else { return Ok(Value::Undefined) }; + let root = Value::String(flat.clone()); + new_iterator(interp, proto, IterState::String { text: Some(flat), pos: 0 }, root) +} + +/// The state of the iterator `this`, or a `TypeError` naming `what` when `this` is not one. +fn state_of<'a>(interp: &'a mut Interp, this: &Value, string: bool, what: &str) -> JsResult<&'a mut IterState> { + let ok = match this { + Value::Object(o) => match interp.heap.object(*o).map(|x| &x.class) { + Some(Class::Iterator(s)) => matches!(**s, IterState::String { .. }) == string, + _ => false, + }, + _ => false, + }; + if !ok { + return Err(interp.type_error(&format!("{what}.next was called on a value that is not an {what}"))); + } + match this.as_object().and_then(|o| interp.heap.object_mut(o)).map(|x| &mut x.class) { + Some(Class::Iterator(s)) => Ok(s), + _ => Err(crate::interp::Abrupt::Internal("iterator state went missing".into())), + } +} + +/// ToLength (section 7.1.20). +fn to_length(interp: &mut Interp, v: &Value) -> JsResult { + let n = interp.to_number(v)?; + if n.is_nan() || n <= 0.0 { + return Ok(0.0); + } + Ok(n.trunc().min(9_007_199_254_740_991.0)) +} + +/// `%ArrayIteratorPrototype%.next()` (section 22.1.5.2.1). +fn array_iterator_next(interp: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult { + let IterState::Array { target, next, kind } = *state_of(interp, &this, false, "Array Iterator")? else { + return Err(crate::interp::Abrupt::Internal("not an Array Iterator".into())); + }; + interp.use_fuel()?; + let Some(a) = target else { return iter_result(interp, Value::Undefined, true) }; + // Reading `length` and the element can run script that collects, and that script can finish + // the iterator, which then no longer holds the object. + let roots = [this.clone(), Value::Object(a)]; + interp.rooted(&roots, |interp| array_step(interp, &this, a, next, kind)) +} + +/// One step of an Array Iterator over `a` at index `next`, with `this` and `a` kept reachable. +fn array_step(interp: &mut Interp, this: &Value, a: ObjId, next: f64, kind: ArrayKind) -> JsResult { + let len = interp.get_from(a, &key("length"), &Value::Object(a))?; + let len = to_length(interp, &len)?; + if next >= len { + if let IterState::Array { target, .. } = state_of(interp, this, false, "Array Iterator")? { + *target = None; + } + return iter_result(interp, Value::Undefined, true); + } + if let IterState::Array { next: n, .. } = state_of(interp, this, false, "Array Iterator")? { + *n = next + 1.0; + } + let index = Value::Number(next); + let value = match kind { + ArrayKind::Keys => index, + ArrayKind::Values | ArrayKind::Entries => { + let k = number_to_str(next).flat(); + let v = interp.get_from(a, &k, &Value::Object(a))?; + if kind == ArrayKind::Values { + v + } else { + let pair = interp.rooted(std::slice::from_ref(&v), |i| new_array(i, 0))?; + interp.rooted(&[Value::Object(pair), v.clone()], |i| { + create_at(i, pair, 0.0, index)?; + create_at(i, pair, 1.0, v.clone()) + })?; + Value::Object(pair) + } + } + }; + iter_result(interp, value, false) +} + +/// `%StringIteratorPrototype%.next()` (section 21.1.5.2.1): the next code point, a surrogate +/// pair kept together and a lone surrogate given alone. +fn string_iterator_next(interp: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult { + interp.use_fuel()?; + let state = state_of(interp, &this, true, "String Iterator")?; + let IterState::String { text, pos } = state else { return Err(crate::interp::Abrupt::Internal("not a String Iterator".into())) }; + let Some(s) = text.as_ref() else { return iter_result(interp, Value::Undefined, true) }; + let units = s.flat(); + let Some(&first) = units.get(*pos) else { + *text = None; + return iter_result(interp, Value::Undefined, true); + }; + let pair = (0xD800..0xDC00).contains(&first) && units.get(*pos + 1).is_some_and(|u| (0xDC00..0xE000).contains(u)); + let width = if pair { 2 } else { 1 }; + let piece = units.get(*pos..*pos + width).map(<[u16]>::to_vec).unwrap_or_default(); + *pos += width; + interp.rooted(std::slice::from_ref(&this), |interp| { + let v = new_string(interp, piece)?; + iter_result(interp, v, false) + }) +} diff --git a/crates/js/src/builtins/json.rs b/crates/js/src/builtins/json.rs index 364ec99696..6f659922b2 100644 --- a/crates/js/src/builtins/json.rs +++ b/crates/js/src/builtins/json.rs @@ -556,7 +556,7 @@ fn resolve_rooted(interp: &mut Interp, settings: &Settings, holder: ObjId, k: &K } } Ok(match v { - Value::Undefined => Item::Skip, + Value::Undefined | Value::Symbol(_) => Item::Skip, Value::Object(_) if interp.is_callable(&v) => Item::Skip, Value::Object(o) => Item::Container(o), other => Item::Primitive(other), @@ -579,7 +579,7 @@ fn unwrap_primitive(interp: &mut Interp, v: &Value, as_string: bool) -> JsResult }; let (hint, name) = if string { (Hint::String, "toString") } else { (Hint::Number, "valueOf") }; let p = if reaches_prototype(interp, *o, proto, name)? { primitive } else { interp.to_primitive(v, hint)? }; - Ok(Some(if string { Value::String(interp.primitive_to_str(&p)) } else { Value::Number(interp.to_number(&p)?) })) + Ok(Some(if string { Value::String(interp.to_str(&p)?) } else { Value::Number(interp.to_number(&p)?) })) } /// Whether looking up `name` from `o` reaches the object `proto` on the prototype chain before @@ -637,7 +637,7 @@ fn write_primitive(interp: &mut Interp, out: &mut Builder, v: &Value) -> JsResul let units = flat_charged(i, s)?; write_quoted(i, out, &units) }), - Value::Undefined | Value::Object(_) => Ok(()), + Value::Undefined | Value::Object(_) | Value::Symbol(_) => Ok(()), } } diff --git a/crates/js/src/builtins/object.rs b/crates/js/src/builtins/object.rs index af41bb7782..48fdbb6eda 100644 --- a/crates/js/src/builtins/object.rs +++ b/crates/js/src/builtins/object.rs @@ -7,6 +7,7 @@ use super::{ELEMENT_BYTES, arg, create_at, method, new_array}; use crate::heap::{CONFIGURABLE, ENUMERABLE, Key, OBJECT_BYTES, OPEN, ObjId, Object, Prop, WRITABLE, key}; use crate::interp::{Desc, Interp, JsResult}; +use crate::symbol::PropKey; use crate::value::{Str, Value}; pub(super) fn install(interp: &mut Interp, object: ObjId) -> JsResult<()> { @@ -119,6 +120,14 @@ fn names_array(interp: &mut Interp, names: Vec) -> JsResult { }) } +/// The object's own property keys: its names, then its Symbols (ECMA-262 11th edition, section +/// 9.1.11). +fn own_prop_keys(interp: &mut Interp, o: ObjId) -> JsResult> { + let mut keys: Vec = interp.own_keys(o)?.into_iter().map(PropKey::Str).collect(); + keys.extend(interp.own_symbols(o)?.into_iter().map(PropKey::Sym)); + Ok(keys) +} + /// `Object.getPrototypeOf` (section 15.2.3.2). fn get_prototype_of(interp: &mut Interp, _: Value, args: &[Value], _: bool) -> JsResult { let o = interp.to_object(&arg(args, 0))?; @@ -129,8 +138,8 @@ fn get_prototype_of(interp: &mut Interp, _: Value, args: &[Value], _: bool) -> J fn get_own_property_descriptor(interp: &mut Interp, _: Value, args: &[Value], _: bool) -> JsResult { let o = interp.to_object(&arg(args, 0))?; interp.rooted(&[Value::Object(o)], |interp| { - let k = interp.to_key(&arg(args, 1))?; - match interp.get_own_property(o, &k)? { + let k = interp.to_prop_key(&arg(args, 1))?; + match interp.get_own_pk(o, &k)? { Some(p) => from_prop(interp, &p), None => Ok(Value::Undefined), } @@ -166,10 +175,10 @@ fn create(interp: &mut Interp, _: Value, args: &[Value], _: bool) -> JsResult JsResult { let o = require_object(interp, &arg(args, 0), "defineProperty")?; - interp.with_key(&arg(args, 1), |interp, k| { + interp.with_prop_key(&arg(args, 1), |interp, k| { let desc = to_desc(interp, &arg(args, 2))?; let roots = desc_values(&desc); - interp.rooted(&roots, |interp| interp.define_own_property(o, k, &desc, true)) + interp.rooted(&roots, |interp| interp.define_own_pk(o, k, &desc, true)) })?; Ok(Value::Object(o)) } @@ -189,12 +198,12 @@ fn define_all(interp: &mut Interp, o: ObjId, props: &Value) -> JsResult<()> { interp.temp_roots.push(Value::Object(p)); let r = (|| { let mut descs = Vec::new(); - for k in interp.own_keys(p)? { + for k in own_prop_keys(interp, p)? { interp.use_fuel()?; - if !interp.get_own_property(p, &k)?.is_some_and(|prop| prop.enumerable()) { + if !interp.get_own_pk(p, &k)?.is_some_and(|prop| prop.enumerable()) { continue; } - let v = interp.get_from(p, &k, &Value::Object(p))?; + let v = interp.get_value_pk(&Value::Object(p), &k)?; interp.temp_roots.push(v.clone()); let desc = to_desc(interp, &v)?; interp.temp_roots.extend(desc_values(&desc)); @@ -202,7 +211,7 @@ fn define_all(interp: &mut Interp, o: ObjId, props: &Value) -> JsResult<()> { } for (k, desc) in descs { interp.use_fuel()?; - interp.define_own_property(o, k, &desc, true)?; + interp.define_own_pk(o, k, &desc, true)?; } Ok(()) })(); @@ -214,9 +223,9 @@ fn define_all(interp: &mut Interp, o: ObjId, props: &Value) -> JsResult<()> { /// then makes the object non-extensible (sections 15.2.3.8 and 15.2.3.9). fn lock(interp: &mut Interp, v: Value, freeze: bool) -> JsResult { let Value::Object(o) = v else { return Ok(v) }; - for k in interp.own_keys(o)? { + for k in own_prop_keys(interp, o)? { interp.use_fuel()?; - let Some(prop) = interp.get_own_property(o, &k)? else { continue }; + let Some(prop) = interp.get_own_pk(o, &k)? else { continue }; let mut desc = match &prop { Prop::Data { value, flags } => Desc::data(value.clone(), *flags), Prop::Accessor { get, set, flags } => Desc { @@ -231,7 +240,7 @@ fn lock(interp: &mut Interp, v: Value, freeze: bool) -> JsResult { if freeze && desc.is_data() { desc.writable = Some(false); } - interp.define_own_property(o, k, &desc, true)?; + interp.define_own_pk(o, k, &desc, true)?; } if let Some(obj) = interp.heap.object_mut(o) { obj.extensible = false; @@ -263,9 +272,9 @@ fn prevent_extensions(interp: &mut Interp, _: Value, args: &[Value], _: bool) -> fn locked(interp: &mut Interp, v: &Value, frozen: bool) -> JsResult { let Value::Object(o) = v else { return Ok(Value::Bool(true)) }; let o = *o; - for k in interp.own_keys(o)? { + for k in own_prop_keys(interp, o)? { interp.use_fuel()?; - let Some(prop) = interp.get_own_property(o, &k)? else { continue }; + let Some(prop) = interp.get_own_pk(o, &k)? else { continue }; if prop.configurable() || (frozen && matches!(prop, Prop::Data { flags, .. } if flags & WRITABLE != 0)) { return Ok(Value::Bool(false)); } diff --git a/crates/js/src/builtins/symbol.rs b/crates/js/src/builtins/symbol.rs new file mode 100644 index 0000000000..f0afe7b2f8 --- /dev/null +++ b/crates/js/src/builtins/symbol.rs @@ -0,0 +1,161 @@ +//! `Symbol` (ECMA-262 11th edition, section 19.4, ): +//! the constructor with `Symbol.for`, `Symbol.keyFor` and the well-known Symbols, the methods of +//! `Symbol.prototype`, `Object.getOwnPropertySymbols` (section 19.1.2.10) and +//! `Function.prototype[@@hasInstance]` (section 19.2.3.6). Installed in a realm with +//! [`crate::Options::es2015`] only. + +use super::{arg, constructor, create_at, data, method, native, new_array}; +use crate::heap::{CONFIGURABLE, Class, NativeFn, NativeKind, ObjId, Object, Prop, SYMBOL_BYTES, string_bytes}; +use crate::interp::{Interp, JsResult}; +use crate::symbol::{Es2015Objects, REGISTRY_ENTRY_BYTES, Sym, WellKnown}; +use crate::value::{Str, Value}; + +pub(super) fn install(interp: &mut Interp, object_ctor: ObjId) -> JsResult<()> { + let well_known = WellKnown::new(); + let names = [ + ("iterator", well_known.iterator.clone()), + ("asyncIterator", well_known.async_iterator.clone()), + ("hasInstance", well_known.has_instance.clone()), + ("toPrimitive", well_known.to_primitive.clone()), + ("toStringTag", well_known.to_string_tag.clone()), + ]; + let (to_string_tag, to_primitive, has_instance) = + (well_known.to_string_tag.clone(), well_known.to_primitive.clone(), well_known.has_instance.clone()); + interp.symbols.well_known = Some(well_known); + + let object_proto = interp.intrinsics.object_proto; + let proto = interp.heap.alloc_object(Object::new(Class::Ordinary, Some(object_proto))); + let ctor = native(interp, "Symbol", symbol_ctor, 0, NativeKind::Plain, true)?; + constructor(interp, "Symbol", ctor, proto)?; + method(interp, ctor, "for", symbol_for, 1)?; + method(interp, ctor, "keyFor", key_for, 1)?; + for (name, sym) in names { + data(interp, ctor, name, Value::Symbol(sym), 0)?; + } + method(interp, proto, "toString", to_string, 0)?; + method(interp, proto, "valueOf", value_of, 0)?; + let getter = native(interp, "get description", description, 0, NativeKind::Plain, false)?; + interp.define(proto, crate::heap::key("description"), Prop::Accessor { get: Some(getter), set: None, flags: CONFIGURABLE })?; + interp.define_sym(proto, to_string_tag, Prop::Data { value: Value::str("Symbol"), flags: CONFIGURABLE })?; + sym_method(interp, proto, to_primitive, "[Symbol.toPrimitive]", symbol_to_primitive, 1, CONFIGURABLE)?; + + method(interp, object_ctor, "getOwnPropertySymbols", get_own_property_symbols, 1)?; + let function_proto = interp.intrinsics.function_proto; + let has_instance = sym_method(interp, function_proto, has_instance, "[Symbol.hasInstance]", function_has_instance, 1, 0)?; + // The iterator prototypes and `%ArrayProto_values%` are set when the iterators are installed. + interp.symbols.objects = Some(Es2015Objects { + symbol_proto: proto, + array_iterator_proto: proto, + string_iterator_proto: proto, + array_values: has_instance, + has_instance, + }); + Ok(()) +} + +/// Defines a built-in function as the property `sym` of `on`, with the attribute `flags`. +pub(super) fn sym_method(interp: &mut Interp, on: ObjId, sym: Sym, name: &'static str, f: NativeFn, length: u32, flags: u8) -> JsResult { + let m = native(interp, name, f, length, NativeKind::Plain, false)?; + interp.define_sym(on, sym, Prop::Data { value: Value::Object(m), flags })?; + Ok(m) +} + +/// A new Symbol, its bytes checked against the heap limit and charged to the heap. +fn new_symbol(interp: &mut Interp, description: Option, registered: bool, extra: usize) -> JsResult { + let bytes = SYMBOL_BYTES.saturating_add(extra); + let roots: Vec = description.iter().cloned().map(Value::String).collect(); + interp.rooted(&roots, |i| i.reserve_heap(bytes))?; + interp.heap.bytes = interp.heap.bytes.saturating_add(bytes); + Ok(Sym::new(description, registered)) +} + +/// `Symbol([description])` (section 19.4.1.1). `new Symbol()` throws a `TypeError`. +fn symbol_ctor(interp: &mut Interp, _: Value, args: &[Value], construct: bool) -> JsResult { + if construct { + return Err(interp.type_error("the value is not a constructor")); + } + let description = match arg(args, 0) { + Value::Undefined => None, + d => Some(interp.to_str(&d)?), + }; + new_symbol(interp, description, false, 0).map(Value::Symbol) +} + +/// `Symbol.for(key)` (section 19.4.2.2): the registry's Symbol for the key, made the first time. +fn symbol_for(interp: &mut Interp, _: Value, args: &[Value], _: bool) -> JsResult { + let key = interp.to_str(&arg(args, 0))?; + let units = crate::string_builtins::flat_charged(interp, &key)?; + if let Some(v) = interp.symbols.registry.get(&*units) { + return Ok(v.clone()); + } + let extra = REGISTRY_ENTRY_BYTES.saturating_add(string_bytes(units.len())); + let sym = new_symbol(interp, Some(Str::from_rc(units.clone())), true, extra)?; + interp.symbols.registry.insert(units, Value::Symbol(sym.clone())); + Ok(Value::Symbol(sym)) +} + +/// `Symbol.keyFor(sym)` (section 19.4.2.6). +fn key_for(interp: &mut Interp, _: Value, args: &[Value], _: bool) -> JsResult { + let Value::Symbol(sym) = arg(args, 0) else { return Err(interp.type_error("Symbol.keyFor was given a value that is not a Symbol")) }; + Ok(match sym.description() { + Some(d) if sym.registered() => Value::String(d.clone()), + _ => Value::Undefined, + }) +} + +/// thisSymbolValue (section 19.4.3): a Symbol, or the Symbol of a Symbol object. +fn this_symbol(interp: &mut Interp, this: &Value, name: &str) -> JsResult { + let sym = match this { + Value::Symbol(s) => Some(s.clone()), + Value::Object(o) => match interp.heap.object(*o).map(|x| &x.class) { + Some(Class::Symbol(s)) => Some(s.clone()), + _ => None, + }, + _ => None, + }; + sym.ok_or_else(|| interp.type_error(&format!("Symbol.prototype.{name} was called on a value that is not a Symbol"))) +} + +/// `Symbol.prototype.toString` (section 19.4.3.3): `Symbol(description)`. +fn to_string(interp: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult { + let sym = this_symbol(interp, &this, "toString")?; + interp.descriptive_string(&sym) +} + +/// `Symbol.prototype.valueOf` (section 19.4.3.4). +fn value_of(interp: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult { + this_symbol(interp, &this, "valueOf").map(Value::Symbol) +} + +/// The getter of `Symbol.prototype.description` (section 19.4.3.2). +fn description(interp: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult { + let sym = this_symbol(interp, &this, "description")?; + Ok(sym.description().map_or(Value::Undefined, |d| Value::String(d.clone()))) +} + +/// `Symbol.prototype[@@toPrimitive](hint)` (section 19.4.3.5). +fn symbol_to_primitive(interp: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult { + this_symbol(interp, &this, "[Symbol.toPrimitive]").map(Value::Symbol) +} + +/// `Object.getOwnPropertySymbols(o)` (section 19.1.2.10): the object's own Symbol keys in the +/// order they were added. +fn get_own_property_symbols(interp: &mut Interp, _: Value, args: &[Value], _: bool) -> JsResult { + let o = interp.to_object(&arg(args, 0))?; + interp.rooted(&[Value::Object(o)], |interp| { + let syms = interp.own_symbols(o)?; + let a = new_array(interp, 0)?; + interp.rooted(&[Value::Object(a)], |interp| { + for (i, s) in syms.into_iter().enumerate() { + interp.use_fuel()?; + create_at(interp, a, i as f64, Value::Symbol(s))?; + } + Ok(Value::Object(a)) + }) + }) +} + +/// `Function.prototype[@@hasInstance](v)` (section 19.2.3.6): OrdinaryHasInstance. +fn function_has_instance(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { + interp.ordinary_has_instance(&arg(args, 0), &this).map(Value::Bool) +} diff --git a/crates/js/src/heap.rs b/crates/js/src/heap.rs index f612b00138..2ee57c5fc3 100644 --- a/crates/js/src/heap.rs +++ b/crates/js/src/heap.rs @@ -227,6 +227,10 @@ pub(crate) enum Class { RegExp(Rc), /// A `Date` object and its time value. Date(f64), + /// A Symbol object made by ToObject, with its Symbol (ECMA-262 11th edition, section 19.4). + Symbol(crate::symbol::Sym), + /// An Array Iterator or a String Iterator and how far it has gone (sections 22.1.5 and 21.1.5). + Iterator(Box), ForIn(Box), /// The `Math` object (section 15.8). Math, @@ -312,7 +316,7 @@ impl Class { Class::XmlFilter(_) => "Object", Class::Math => "Math", Class::Json => "JSON", - Class::Ordinary | Class::ForIn(_) => "Object", + Class::Ordinary | Class::ForIn(_) | Class::Symbol(_) | Class::Iterator(_) => "Object", Class::Array { .. } => "Array", Class::Function(_) => "Function", Class::Error(_) => "Error", @@ -331,11 +335,13 @@ pub(crate) struct Object { pub(crate) proto: Option, pub(crate) extensible: bool, pub(crate) props: PropMap, + /// The properties whose keys are Symbols, once the object has one. + pub(crate) syms: Option>, } impl Object { pub(crate) fn new(class: Class, proto: Option) -> Self { - Self { class, proto, extensible: true, props: PropMap::default() } + Self { class, proto, extensible: true, props: PropMap::default(), syms: None } } } @@ -395,6 +401,8 @@ pub(crate) const XML_LIST_BYTES: usize = 96; pub(crate) const XML_REF_BYTES: usize = 8; /// The estimated bytes of a namespace an XML node holds. pub(crate) const XML_NS_BYTES: usize = 48; +/// The estimated bytes of a Symbol without its description. +pub(crate) const SYMBOL_BYTES: usize = 48; /// The estimated bytes of a piece of code without its instructions, tables and strings. const CODE_BYTES: usize = 384; @@ -557,16 +565,34 @@ impl StringSizes { self.bytes += string_bytes(k.len()); } } + + /// Adds a Symbol and its description, once however many values and keys share it. + fn add_symbol(&mut self, s: &crate::symbol::Sym) { + if self.seen.insert(s.addr()) { + self.bytes += SYMBOL_BYTES; + if let Some(d) = s.description() { + self.add(d); + } + } + } } fn mark_value(v: &Value, work: &mut Vec, strings: &mut StringSizes) { match v { Value::Object(o) => work.push(o.0), Value::String(s) => strings.add(s), + Value::Symbol(s) => strings.add_symbol(s), _ => {} } } +fn mark_prop(prop: &Prop, work: &mut Vec, strings: &mut StringSizes) { + match prop { + Prop::Data { value, .. } => mark_value(value, work, strings), + Prop::Accessor { get, set, .. } => work.extend(get.iter().chain(set.iter()).map(|f| f.0)), + } +} + /// The estimated bytes of `code` with the functions nested in it and its source text, for /// charging code made at run time to the heap before anything refers to it. pub(crate) fn code_bytes(code: &Code) -> usize { @@ -626,10 +652,12 @@ fn trace_object(o: &Object, work: &mut Vec, strings: &mut StringSizes) -> u } for (k, prop) in o.props.iter() { strings.add_key(k); - match prop { - Prop::Data { value, .. } => mark_value(value, work, strings), - Prop::Accessor { get, set, .. } => work.extend(get.iter().chain(set.iter()).map(|f| f.0)), - } + mark_prop(prop, work, strings); + } + let syms = o.syms.as_ref().map_or(0, |m| m.len()); + for (k, prop) in o.syms.iter().flat_map(|m| m.iter()) { + strings.add_symbol(k); + mark_prop(prop, work, strings); } let mut extra = 0; match &o.class { @@ -656,6 +684,11 @@ fn trace_object(o: &Object, work: &mut Vec, strings: &mut StringSizes) -> u work.extend(state.object.iter().map(|o| o.0)); strings.bytes += state.keys.iter().map(|k| string_bytes(k.len())).sum::(); } + Class::Symbol(s) => strings.add_symbol(s), + Class::Iterator(state) => match &**state { + crate::builtins::iterator::IterState::Array { target, .. } => work.extend(target.iter().map(|o| o.0)), + crate::builtins::iterator::IterState::String { text, .. } => text.iter().for_each(|s| strings.add(s)), + }, Class::Xml(node) => { work.extend(node.parent.iter().chain(&node.attrs).chain(&node.children).map(|o| o.0)); strings.add(&node.value); @@ -682,7 +715,7 @@ fn trace_object(o: &Object, work: &mut Vec, strings: &mut StringSizes) -> u } _ => {} } - OBJECT_BYTES + PROP_BYTES * o.props.len() + extra + OBJECT_BYTES + PROP_BYTES * (o.props.len() + syms) + extra } fn add_name(name: &XmlName, strings: &mut StringSizes) { diff --git a/crates/js/src/host.rs b/crates/js/src/host.rs index 4c18d0f76f..967d5e3656 100644 --- a/crates/js/src/host.rs +++ b/crates/js/src/host.rs @@ -243,6 +243,7 @@ impl Interp { Ok(Data::String(s.to_rust_string())) } Value::Object(id) => self.read_object(*id, r), + Value::Symbol(_) => Err(self.data_error(r, ErrorType::Type, "is a Symbol, not plain data")), } } diff --git a/crates/js/src/interp.rs b/crates/js/src/interp.rs index 24c33d2fc5..13ac5cd834 100644 --- a/crates/js/src/interp.rs +++ b/crates/js/src/interp.rs @@ -28,6 +28,7 @@ use crate::heap::{ Object, PROP_BYTES, Prop, PropMap, ROPE_BYTES, Roots, WRITABLE, code_bytes, key, string_bytes, }; use crate::string_builtins::flat_charged; +use crate::symbol::PropKey; use crate::value::{Str, Value, array_index, index_key, number_to_str, string_to_number, to_int32, to_uint32}; use crate::{LimitKind, Limits, Options}; @@ -310,6 +311,9 @@ pub(crate) struct Interp { pub(crate) error_mark: Option, /// [`crate::bytecode::Source::strict_writes`] for the scripts the realm runs. pub(crate) strict_writes: bool, + /// The well-known Symbols, `Symbol.for`'s registry and the objects that go with them, in a + /// realm with [`crate::Options::es2015`]. + pub(crate) symbols: crate::symbol::Symbols, } /// The bytes all live [`HeldBytes`] hold, and the bytes dropped holders released that the heap's @@ -540,6 +544,7 @@ impl Interp { finally_sites: Vec::new(), error_mark: None, strict_writes: false, + symbols: crate::symbol::Symbols::default(), }; crate::builtins::install(&mut interp); interp.fuel = limits.fuel; @@ -774,12 +779,15 @@ impl Interp { roots.objects.push(self.global); roots.objects.extend(self.intrinsics.all()); roots.objects.extend(self.files.iter().flat_map(crate::file_classes::Classes::objects)); + roots.values.extend(self.symbols.root_values()); + roots.objects.extend(self.symbols.root_objects()); roots.envs.push(self.global_env); self.heap.collect(&roots); // The collection counts the live total again, so bytes already released are not in it. self.held.released.set(0); self.flattened.set(0); - self.heap.bytes = self.heap.bytes.saturating_add(self.held_bytes).saturating_add(self.held.now.get()); + self.heap.bytes = + self.heap.bytes.saturating_add(self.held_bytes).saturating_add(self.held.now.get()).saturating_add(self.symbols.registry_bytes()); } /// Runs frames until the boundary frame on top returns, and returns its value. @@ -943,13 +951,13 @@ impl Interp { self.frame()?.code.names.get(i as usize).cloned().ok_or_else(|| Abrupt::Internal("name out of range".into())) } - fn strict(&self) -> bool { + pub(crate) fn strict(&self) -> bool { self.frames.last().is_some_and(|f| f.code.strict) } /// Does a property write the running code makes throw when it cannot be made? It does in /// strict mode code and in code from a source with [`crate::bytecode::Source::strict_writes`]. - fn strict_writes(&self) -> bool { + pub(crate) fn strict_writes(&self) -> bool { self.frames.last().is_some_and(|f| f.code.strict || f.code.source.strict_writes) } @@ -1416,12 +1424,13 @@ impl Interp { } /// The prototype a primitive's properties are looked up on. - fn primitive_proto(&mut self, v: &Value, k: &[u16]) -> JsResult { + pub(crate) fn primitive_proto(&mut self, v: &Value, k: &[u16]) -> JsResult { match v { Value::Object(o) => Ok(*o), Value::String(_) => Ok(self.intrinsics.string_proto), Value::Number(_) => Ok(self.intrinsics.number_proto), Value::Bool(_) => Ok(self.intrinsics.boolean_proto), + Value::Symbol(_) => Ok(self.symbols.objects.map_or(self.intrinsics.object_proto, |o| o.symbol_proto)), Value::Undefined | Value::Null => { let key = String::from_utf16_lossy(k); let base = if matches!(v, Value::Null) { "null" } else { "undefined" }; @@ -1520,7 +1529,7 @@ impl Interp { } } - fn reject_bool(&mut self, throw: bool, k: &[u16], why: &str) -> JsResult { + pub(crate) fn reject_bool(&mut self, throw: bool, k: &[u16], why: &str) -> JsResult { if throw { let key = String::from_utf16_lossy(k); return Err(self.type_error(&format!("cannot define property '{key}': {why}"))); @@ -1674,7 +1683,7 @@ impl Interp { r } - fn reject(&mut self, throw: bool, k: &[u16], why: &str) -> JsResult<()> { + pub(crate) fn reject(&mut self, throw: bool, k: &[u16], why: &str) -> JsResult<()> { if throw { let key = String::from_utf16_lossy(k); return Err(self.type_error(&format!("cannot assign to property '{key}': {why}"))); @@ -1780,7 +1789,7 @@ impl Interp { } /// PutValue on a property reference (section 8.7.2), whose base may be a primitive. - fn put_value(&mut self, base: &Value, k: Key, v: Value) -> JsResult<()> { + pub(crate) fn put_value(&mut self, base: &Value, k: Key, v: Value) -> JsResult<()> { if self.options.e4x && self.is_xml(base) { return self.xml_put(base, &Value::String(Str::from_rc(k)), &v); } @@ -1837,6 +1846,8 @@ impl Interp { let key = match k { Some(Value::String(s)) if s.len() > NAMED_KEY_UNITS => None, Some(Value::Object(_)) | None => None, + Some(Value::Symbol(s)) if s.description().is_some_and(|d| d.len() > NAMED_KEY_UNITS) => None, + Some(Value::Symbol(s)) => Some(self.sym_name(s)?), Some(k) => Some(self.to_str(k)?.to_rust_string()), }; let base = if matches!(base, Value::Null) { "null" } else { "undefined" }; @@ -1860,8 +1871,11 @@ impl Interp { return Ok(()); } self.check_coercible(&base, Some(&k), true)?; - let name = self.to_key(&k)?; - self.replace(1, Value::String(Str::from_rc(name))) + let key = match self.to_prop_key(&k)? { + PropKey::Str(name) => Value::String(Str::from_rc(name)), + PropKey::Sym(s) => Value::Symbol(s), + }; + self.replace(1, key) } fn op_get_index(&mut self, with_this: bool) -> JsResult<()> { @@ -1878,7 +1892,7 @@ impl Interp { return self.replace(2, v); } self.check_coercible(&base, Some(&k), false)?; - let v = self.with_key(&k, |i, name| i.get_value(&base, &name))?; + let v = self.with_prop_key(&k, |i, key| i.get_value_pk(&base, &key))?; self.replace(2, v)?; if with_this { self.push(base) } else { Ok(()) } } @@ -1891,8 +1905,8 @@ impl Interp { self.xml_put(&base, &k, &v)?; return self.replace(3, v); } - let name = self.to_key(&k)?; - self.put_value(&base, name, v.clone())?; + let key = self.to_prop_key(&k)?; + self.put_value_pk(&base, key, v.clone())?; self.replace(3, v) } @@ -1917,25 +1931,25 @@ impl Interp { return self.replace(2, Value::Bool(r)); } self.check_coercible(&base, Some(&k), false)?; - let name = self.to_key(&k)?; + let key = self.to_prop_key(&k)?; let o = self.to_object(&base)?; let strict = self.strict(); - let r = self.delete(o, &name, strict)?; + let r = self.delete_pk(o, &key, strict)?; self.replace(2, Value::Bool(r)) } - fn inc_property(&mut self, base: &Value, name: Key, prefix: bool, dec: bool) -> JsResult { - let v = self.get_value(base, &name)?; + fn inc_property(&mut self, base: &Value, key: PropKey, prefix: bool, dec: bool) -> JsResult { + let v = self.get_value_pk(base, &key)?; let old = self.to_number(&v)?; let new = if dec { old - 1.0 } else { old + 1.0 }; - self.put_value(base, name, Value::Number(new))?; + self.put_value_pk(base, key, Value::Number(new))?; Ok(Value::Number(if prefix { new } else { old })) } fn op_inc_member(&mut self, n: u32, prefix: bool, dec: bool) -> JsResult<()> { let name = self.name(n)?; let base = self.peek(0)?; - let r = self.inc_property(&base, name, prefix, dec)?; + let r = self.inc_property(&base, PropKey::Str(name), prefix, dec)?; self.replace(1, r) } @@ -1950,7 +1964,7 @@ impl Interp { return self.replace(2, Value::Number(if prefix { new } else { old })); } self.check_coercible(&base, Some(&k), false)?; - let r = self.with_key(&k, |i, name| i.inc_property(&base, name, prefix, dec))?; + let r = self.with_prop_key(&k, |i, key| i.inc_property(&base, key, prefix, dec))?; self.replace(2, r) } @@ -2481,6 +2495,7 @@ impl Interp { } else { self.define(a, key("callee"), Prop::Data { value: Value::Object(callee), flags: HIDDEN })?; } + crate::builtins::iterator::define_arguments_iterator(self, a)?; Ok(a) } @@ -2745,16 +2760,22 @@ impl Interp { Value::Bool(_) => "boolean", Value::Number(_) => "number", Value::String(_) => "string", + Value::Symbol(_) => "symbol", Value::Object(_) if self.options.e4x && self.is_xml(v) => "xml", Value::Object(_) if self.is_callable(v) => "function", Value::Object(_) => "object", } } - /// ToPrimitive (section 9.1) through [[DefaultValue]] (section 8.12.8). + /// ToPrimitive (section 9.1) through [[DefaultValue]] (section 8.12.8). In a realm with + /// [`crate::Options::es2015`], an object's `@@toPrimitive` method is called first when it + /// has one (ECMA-262 11th edition, section 7.1.1). #[allow(clippy::wrong_self_convention)] pub(crate) fn to_primitive(&mut self, v: &Value, hint: Hint) -> JsResult { let Value::Object(o) = v else { return Ok(v.clone()) }; + if let Some(r) = self.exotic_to_primitive(*o, v, hint)? { + return Ok(r); + } // Without a hint, a Date object converts as with the String hint. let date = hint == Hint::Default && matches!(self.heap.object(*o).map(|ob| &ob.class), Some(Class::Date(_))); let order = if hint == Hint::String || date { ["toString", "valueOf"] } else { ["valueOf", "toString"] }; @@ -2778,6 +2799,7 @@ impl Interp { Value::Bool(b) => f64::from(u8::from(*b)), Value::Number(n) => *n, Value::String(s) => string_to_number(&flat_charged(self, s)?), + Value::Symbol(_) => return Err(self.type_error("cannot convert a Symbol value to a number")), Value::Object(_) => { let p = self.to_primitive(v, Hint::Number)?; return self.to_number(&p); @@ -2785,7 +2807,9 @@ impl Interp { }) } - /// ToString applied to a primitive. + /// ToString applied to a primitive, with a Symbol written as `Symbol(description)` for + /// messages, its description cut as [`crate::symbol::Sym::message_name`] cuts it; + /// [`Self::to_str`] refuses a Symbol. pub(crate) fn primitive_to_str(&mut self, v: &Value) -> Str { match v { Value::Undefined => Str::from("undefined"), @@ -2798,12 +2822,22 @@ impl Interp { } Value::String(s) => s.clone(), Value::Object(_) => Str::from("[object]"), + Value::Symbol(s) => { + let (units, _) = s.message_name(); + self.heap.bytes += string_bytes(units.len()); + Str::from_units(units) + } } } + /// ToString (section 9.8); a Symbol throws a `TypeError` (ECMA-262 11th edition, section + /// 7.1.17). #[allow(clippy::wrong_self_convention)] pub(crate) fn to_str(&mut self, v: &Value) -> JsResult { let p = self.to_primitive(v, Hint::String)?; + if matches!(p, Value::Symbol(_)) { + return Err(self.type_error("cannot convert a Symbol value to a string")); + } Ok(self.primitive_to_str(&p)) } @@ -2854,6 +2888,7 @@ impl Interp { Value::Bool(b) => (Class::Boolean(*b), self.intrinsics.boolean_proto), Value::Number(n) => (Class::Number(*n), self.intrinsics.number_proto), Value::String(s) => (Class::String(s.clone()), self.intrinsics.string_proto), + Value::Symbol(s) => (Class::Symbol(s.clone()), self.primitive_proto(v, &[])?), }; Ok(self.heap.alloc_object(Object::new(class, Some(proto)))) } @@ -2932,8 +2967,8 @@ impl Interp { return self.xml_has(b, a).map(Value::Bool); } let Value::Object(o) = b else { return Err(self.type_error("the right side of 'in' is not an object")) }; - let k = self.to_key(a)?; - self.has_property(*o, &k).map(Value::Bool) + let k = self.to_prop_key(a)?; + self.has_pk(*o, &k).map(Value::Bool) } } } @@ -2949,8 +2984,10 @@ impl Interp { let pa = self.to_primitive(a, Hint::Default)?; let pb = self.to_primitive(b, Hint::Default)?; if matches!(pa, Value::String(_)) || matches!(pb, Value::String(_)) { - let sa = self.primitive_to_str(&pa); - let sb = self.primitive_to_str(&pb); + // Both are primitives, so this converts them without running script code; a Symbol + // throws. + let sa = self.to_str(&pa)?; + let sb = self.to_str(&pb)?; return self.concat(&sa, &sb).map(Value::String); } Ok(Value::Number(self.to_number(&pa)? + self.to_number(&pb)?)) @@ -2995,29 +3032,45 @@ impl Interp { (Value::Number(_), Value::Number(_)) | (Value::String(_), Value::String(_)) | (Value::Bool(_), Value::Bool(_)) + | (Value::Symbol(_), Value::Symbol(_)) | (Value::Object(_), Value::Object(_)) => return Ok(strict_eq(&x, &y)), (Value::Number(n), Value::String(s)) | (Value::String(s), Value::Number(n)) => { return Ok(*n == string_to_number(&flat_charged(self, s)?)); } (Value::Bool(v), _) => x = Value::Number(f64::from(u8::from(*v))), (_, Value::Bool(v)) => y = Value::Number(f64::from(u8::from(*v))), - (Value::Number(_) | Value::String(_), Value::Object(_)) => y = self.to_primitive(&y, Hint::Default)?, - (Value::Object(_), Value::Number(_) | Value::String(_)) => x = self.to_primitive(&x, Hint::Default)?, + (Value::Number(_) | Value::String(_) | Value::Symbol(_), Value::Object(_)) => y = self.to_primitive(&y, Hint::Default)?, + (Value::Object(_), Value::Number(_) | Value::String(_) | Value::Symbol(_)) => x = self.to_primitive(&x, Hint::Default)?, _ => return Ok(false), } } } - /// `instanceof` (sections 11.8.6 and 15.3.5.3). + /// `instanceof` (sections 11.8.6 and 15.3.5.3). In a realm with [`crate::Options::es2015`], + /// the right side's `@@hasInstance` method answers when it has one (ECMA-262 11th edition, + /// section 12.10.4). fn instance_of(&mut self, v: &Value, f: &Value) -> JsResult { + if let Some(r) = self.has_instance_hook(v, f)? { + return Ok(r); + } if !self.is_callable(f) { return Err(self.type_error("the right side of 'instanceof' is not a function")); } - let Some(mut fid) = f.as_object() else { return Ok(false) }; - // A bound function answers for its target (section 15.3.4.5.3). + self.ordinary_has_instance(v, f) + } + + /// OrdinaryHasInstance (ECMA-262 11th edition, section 7.3.21): `false` when `f` is not a + /// function. + pub(crate) fn ordinary_has_instance(&mut self, v: &Value, f: &Value) -> JsResult { + let Some(mut fid) = f.as_object().filter(|_| self.is_callable(f)) else { return Ok(false) }; + // A bound function answers for its target (section 15.3.4.5.3), or the target's own + // `@@hasInstance` method does. while let Some(Func::Bound { target, .. }) = self.func_of(&Value::Object(fid)) { self.use_fuel()?; fid = target; + if let Some(r) = self.bound_target_hook(v, fid)? { + return Ok(r); + } } let f = &Value::Object(fid); let Value::Object(mut o) = v.clone() else { return Ok(false) }; @@ -3048,6 +3101,7 @@ impl Interp { Value::Number(n) => crate::JsValue::Number(*n), Value::String(s) => crate::JsValue::String(s.to_rust_string()), Value::Object(o) => crate::JsValue::Object(self.heap.object(*o).map_or("Object", |o| o.class.name()).to_string()), + Value::Symbol(s) => crate::JsValue::Symbol(s.description().map(Str::to_rust_string)), } } @@ -3068,6 +3122,13 @@ impl Interp { Value::str(&s) } crate::JsValue::Object(_) => Value::Object(self.new_object()), + crate::JsValue::Symbol(description) => { + let units: Option> = description.map(|d| d.encode_utf16().collect()); + let bytes = crate::heap::SYMBOL_BYTES + units.as_ref().map_or(0, |u| string_bytes(u.len())); + self.reserve_heap(bytes)?; + self.heap.bytes += bytes; + Value::Symbol(crate::symbol::Sym::new(units.map(Str::from_units), false)) + } }) } @@ -3127,7 +3188,7 @@ impl Desc { } /// The attribute flags the descriptor gives, each absent one taken from `default`. - fn flags_or(&self, default: u8) -> u8 { + pub(crate) fn flags_or(&self, default: u8) -> u8 { let pick = |field: Option, bit: u8| match field { Some(true) => bit, Some(false) => 0, @@ -3147,7 +3208,7 @@ pub(crate) fn same_value(a: &Value, b: &Value) -> bool { /// Steps 5 to 12 of [[DefineOwnProperty]] (section 8.12.9) for an existing property: the /// property after `desc` is applied, or `None` when the change is not allowed. -fn merge_desc(current: &Prop, desc: &Desc) -> Option { +pub(crate) fn merge_desc(current: &Prop, desc: &Desc) -> Option { let flags = current.flags(); let configurable = flags & CONFIGURABLE != 0; if !configurable { @@ -3203,6 +3264,7 @@ pub(crate) fn strict_eq(a: &Value, b: &Value) -> bool { (Value::String(x), Value::String(y)) => x == y, (Value::Bool(x), Value::Bool(y)) => x == y, (Value::Object(x), Value::Object(y)) => x == y, + (Value::Symbol(x), Value::Symbol(y)) => x == y, _ => false, } } diff --git a/crates/js/src/lib.rs b/crates/js/src/lib.rs index 1561d71dfe..c5e45af08f 100644 --- a/crates/js/src/lib.rs +++ b/crates/js/src/lib.rs @@ -46,6 +46,17 @@ //! those of ECMAScript 5.1 above. XML trees live in the heap, and parsing, copying, comparing and //! serializing them, and evaluating XPath on them, use no native recursion and take fuel for each //! node. +//! +//! With [`Options::es2015`], the realm also has `Symbol` (ECMA-262 11th edition, section 19.4, +//! ): `Symbol.for` and `Symbol.keyFor` over a registry +//! that lasts as long as the realm, the well-known Symbols `iterator`, `asyncIterator`, +//! `hasInstance`, `toPrimitive` and `toStringTag` with the hooks ToPrimitive, `instanceof` and +//! `Object.prototype.toString` read, Symbol-keyed properties with `Object.getOwnPropertySymbols`, +//! and iterator objects with a `next` method from `Array.prototype.values`, `keys`, `entries` and +//! `@@iterator`, `String.prototype[@@iterator]` (by code point) and every `arguments` object. A +//! Symbol converted to a string or a number without `String(symbol)` or `toString` throws a +//! `TypeError`. Every iterator step takes fuel, and every Symbol and registry entry counts against +//! the heap limit. #![forbid(unsafe_code)] pub mod ast; @@ -68,6 +79,7 @@ mod regexp; mod regexp_builtins; mod regexp_vm; mod string_builtins; +mod symbol; mod token; mod value; mod xml; @@ -100,11 +112,15 @@ pub struct Options { pub max_source_units: usize, /// Read and run E4X (ECMA-357). Off, XML syntax is an error and a realm has no XML built-ins. pub e4x: bool, + /// Give a realm the later editions' built-ins this engine has: `Symbol` with Symbol-keyed + /// properties and the iterators of arrays, strings and `arguments` objects. Off, a realm has + /// the ES5.1 built-ins only, as the app's scripts expect. + pub es2015: bool, } impl Default for Options { fn default() -> Self { - Self { strict: false, preprocessor_lines: false, max_depth: DEFAULT_MAX_DEPTH, max_source_units: 64 << 20, e4x: false } + Self { strict: false, preprocessor_lines: false, max_depth: DEFAULT_MAX_DEPTH, max_source_units: 64 << 20, e4x: false, es2015: false } } } @@ -209,6 +225,8 @@ mod host_tests; #[cfg(test)] mod interp_tests; #[cfg(test)] +mod symbol_tests; +#[cfg(test)] mod tests; #[cfg(test)] mod text_tests; diff --git a/crates/js/src/realm.rs b/crates/js/src/realm.rs index ee2cd364f8..08d9913948 100644 --- a/crates/js/src/realm.rs +++ b/crates/js/src/realm.rs @@ -109,7 +109,8 @@ impl Interrupt { } } -/// A value passed between a script and the host. An object is given by its class name. +/// A value passed between a script and the host. An object is given by its class name, and a +/// Symbol by its description; a Symbol the host passes in is a new Symbol each time. #[derive(Clone, Debug, PartialEq)] pub enum JsValue { Undefined, @@ -118,6 +119,7 @@ pub enum JsValue { Number(f64), String(String), Object(String), + Symbol(Option), } #[derive(Clone, Debug, PartialEq, Eq)] diff --git a/crates/js/src/string_builtins.rs b/crates/js/src/string_builtins.rs index eed08f96bd..c2787b5a56 100644 --- a/crates/js/src/string_builtins.rs +++ b/crates/js/src/string_builtins.rs @@ -209,6 +209,8 @@ pub(crate) fn find(interp: &mut Interp, hay: &[u16], needle: &[u16], from: usize /// `String(value)` and `new String(value)` (sections 15.5.1 and 15.5.2). fn string_ctor(interp: &mut Interp, _: Value, args: &[Value], construct: bool) -> JsResult { let s = match args.first() { + // `String(symbol)` gives `Symbol(description)` (ECMA-262 11th edition, section 21.1.1.1). + Some(Value::Symbol(sym)) if !construct => return interp.descriptive_string(sym), Some(v) => interp.to_str(v)?, None => Str::from(""), }; diff --git a/crates/js/src/symbol.rs b/crates/js/src/symbol.rs new file mode 100644 index 0000000000..2c25ebd099 --- /dev/null +++ b/crates/js/src/symbol.rs @@ -0,0 +1,581 @@ +//! Symbols (ECMA-262 11th edition, section 6.1.5, ) and +//! the properties they name. +//! +//! A Symbol is a value with its own identity and an optional description; two Symbols are equal +//! only when they are the same Symbol. An object keeps its Symbol-keyed properties apart from its +//! string-keyed ones, in the order they were added, so `for-in`, `Object.keys`, +//! `Object.getOwnPropertyNames` and `JSON` see only names, and `Object.getOwnPropertySymbols` sees +//! only Symbols. `Symbol.for`'s registry belongs to the realm and lives as long as it does; each +//! entry counts against the heap limit. A realm without [`crate::Options::es2015`] makes no Symbol, +//! so its scripts run as before. + +use std::collections::HashMap; +use std::hash::{Hash, Hasher}; +use std::rc::Rc; + +use crate::heap::{ObjId, PROP_BYTES, Prop, WRITABLE}; +use crate::interp::{Desc, Hint, Interp, JsResult, merge_desc}; +use crate::value::{Str, Value}; + +/// A Symbol value. Clones share the Symbol; equality and hashing compare identity. +#[derive(Clone)] +pub(crate) struct Sym(Rc); + +struct SymData { + description: Option, + /// `Symbol.for` made it, and the registry holds it under its description. + registered: bool, +} + +impl Sym { + pub(crate) fn new(description: Option, registered: bool) -> Self { + Sym(Rc::new(SymData { description, registered })) + } + + pub(crate) fn description(&self) -> Option<&Str> { + self.0.description.as_ref() + } + + pub(crate) fn registered(&self) -> bool { + self.0.registered + } + + /// An address that identifies the Symbol, for counting it once. + pub(crate) fn addr(&self) -> usize { + Rc::as_ptr(&self.0) as *const () as usize + } + + /// `Symbol(description)` for a message, with at most [`NAMED_UNITS`] units of the description + /// followed by `...` when it has more, and the work reading them took: the rope nodes visited + /// plus the units read. The description is not flattened or copied whole. + pub(crate) fn message_name(&self) -> (Vec, u64) { + let mut units: Vec = "Symbol(".encode_utf16().collect(); + let mut work = 0; + if let Some(d) = self.description() { + let (part, visited) = d.prefix(NAMED_UNITS, NAMED_NODES); + work = visited.saturating_add(part.len() as u64); + let cut = part.len() < d.len(); + units.extend_from_slice(&part); + if cut { + units.extend("...".encode_utf16()); + } + } + units.push(u16::from(b')')); + (units, work) + } +} + +/// The most units of a Symbol's description a message names. +const NAMED_UNITS: usize = 256; + +/// The most rope nodes read for the units a message names. +const NAMED_NODES: u64 = 4 * NAMED_UNITS as u64; + +impl PartialEq for Sym { + fn eq(&self, other: &Self) -> bool { + Rc::ptr_eq(&self.0, &other.0) + } +} + +impl Eq for Sym {} + +impl Hash for Sym { + fn hash(&self, state: &mut H) { + self.addr().hash(state); + } +} + +impl std::fmt::Debug for Sym { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + write!(f, "{}", String::from_utf16_lossy(&self.message_name().0)) + } +} + +/// An object's Symbol-keyed properties in the order they were added. A removed entry leaves a +/// gap until half the entries are gaps, so removing keeps the order without moving the rest. +#[derive(Clone, Default)] +pub(crate) struct SymProps { + entries: Vec>, + index: HashMap, +} + +impl SymProps { + pub(crate) fn get(&self, k: &Sym) -> Option<&Prop> { + let i = *self.index.get(k)?; + self.entries.get(i)?.as_ref().map(|(_, p)| p) + } + + pub(crate) fn get_mut(&mut self, k: &Sym) -> Option<&mut Prop> { + let i = *self.index.get(k)?; + self.entries.get_mut(i)?.as_mut().map(|(_, p)| p) + } + + /// Sets the property under `k`, keeping its place when it is there already. Returns whether + /// the key is new. + pub(crate) fn insert(&mut self, k: Sym, prop: Prop) -> bool { + if let Some(slot) = self.get_mut(&k) { + *slot = prop; + return false; + } + self.index.insert(k.clone(), self.entries.len()); + self.entries.push(Some((k, prop))); + true + } + + pub(crate) fn remove(&mut self, k: &Sym) -> Option { + let i = self.index.remove(k)?; + let (_, prop) = self.entries.get_mut(i)?.take()?; + if self.entries.len() > 16 && self.index.len() * 2 < self.entries.len() { + self.entries.retain(Option::is_some); + self.index = self.entries.iter().enumerate().filter_map(|(i, e)| e.as_ref().map(|(k, _)| (k.clone(), i))).collect(); + } + Some(prop) + } + + pub(crate) fn len(&self) -> usize { + self.index.len() + } + + pub(crate) fn iter(&self) -> impl Iterator { + self.entries.iter().filter_map(|e| e.as_ref().map(|(k, p)| (k, p))) + } +} + +/// A property key (section 6.1.7): a name or a Symbol. +pub(crate) enum PropKey { + Str(crate::heap::Key), + Sym(Sym), +} + +/// The well-known Symbols a realm has (section 6.1.5.1): `Symbol.iterator` and the others the +/// language reads, with `Symbol.asyncIterator`, which nothing reads yet. +pub(crate) struct WellKnown { + pub(crate) iterator: Sym, + pub(crate) async_iterator: Sym, + pub(crate) has_instance: Sym, + pub(crate) to_primitive: Sym, + pub(crate) to_string_tag: Sym, + /// The five as values, for the collector. + values: Vec, +} + +impl WellKnown { + pub(crate) fn new() -> Self { + let make = |name: &str| Sym::new(Some(Str::from(name)), false); + let (iterator, async_iterator, has_instance, to_primitive, to_string_tag) = ( + make("Symbol.iterator"), + make("Symbol.asyncIterator"), + make("Symbol.hasInstance"), + make("Symbol.toPrimitive"), + make("Symbol.toStringTag"), + ); + let values = [&iterator, &async_iterator, &has_instance, &to_primitive, &to_string_tag].into_iter().cloned().map(Value::Symbol).collect(); + WellKnown { iterator, async_iterator, has_instance, to_primitive, to_string_tag, values } + } +} + +/// The objects of a realm with [`crate::Options::es2015`] that the interpreter itself uses. +#[derive(Clone, Copy)] +pub(crate) struct Es2015Objects { + pub(crate) symbol_proto: ObjId, + pub(crate) array_iterator_proto: ObjId, + pub(crate) string_iterator_proto: ObjId, + /// `%ArrayProto_values%`, the `@@iterator` of every `arguments` object. + pub(crate) array_values: ObjId, + /// `Function.prototype[@@hasInstance]`. + pub(crate) has_instance: ObjId, +} + +/// The estimated bytes of a registry entry without its Symbol. +pub(crate) const REGISTRY_ENTRY_BYTES: usize = 48; + +/// A realm's Symbols: the well-known ones, `Symbol.for`'s registry and the built-in objects that +/// go with them. All are `None` or empty in a realm without [`crate::Options::es2015`]. +#[derive(Default)] +pub(crate) struct Symbols { + pub(crate) well_known: Option, + /// Each key `Symbol.for` was given, with its Symbol as a value. + pub(crate) registry: HashMap, Value>, + pub(crate) objects: Option, +} + +impl Symbols { + /// The values the collector starts from. + pub(crate) fn root_values(&self) -> impl Iterator { + self.well_known.iter().flat_map(|w| w.values.iter()).chain(self.registry.values()) + } + + /// The objects the collector starts from. + pub(crate) fn root_objects(&self) -> Vec { + self.objects.map_or_else(Vec::new, |o| vec![o.symbol_proto, o.array_iterator_proto, o.string_iterator_proto, o.array_values, o.has_instance]) + } + + /// The bytes the registry's entries hold besides their Symbols, which a collection adds. + pub(crate) fn registry_bytes(&self) -> usize { + self.registry.len().saturating_mul(REGISTRY_ENTRY_BYTES) + } +} + +impl Interp { + /// ToPropertyKey (section 7.1.14): a Symbol, or an object whose primitive value is one, stays a + /// Symbol; any other value becomes a name. + #[allow(clippy::wrong_self_convention)] + pub(crate) fn to_prop_key(&mut self, v: &Value) -> JsResult { + match v { + Value::Symbol(s) => Ok(PropKey::Sym(s.clone())), + Value::Object(_) => match self.to_primitive(v, Hint::String)? { + Value::Symbol(s) => Ok(PropKey::Sym(s)), + p => self.to_key(&p).map(PropKey::Str), + }, + _ => self.to_key(v).map(PropKey::Str), + } + } + + /// Runs `f` with the key [`Self::to_prop_key`] makes from `v`, kept reachable while `f` runs + /// when it was converted from another value. + pub(crate) fn with_prop_key(&mut self, v: &Value, f: impl FnOnce(&mut Self, PropKey) -> JsResult) -> JsResult { + match v { + Value::Symbol(s) => f(self, PropKey::Sym(s.clone())), + Value::Object(_) => { + let p = self.to_primitive(v, Hint::String)?; + if let Value::Symbol(s) = p { + return f(self, PropKey::Sym(s)); + } + self.rooted(std::slice::from_ref(&p), |i| i.with_key(&p, |i, k| f(i, PropKey::Str(k)))) + } + _ => self.with_key(v, |i, k| f(i, PropKey::Str(k))), + } + } + + /// [`Sym::message_name`] as code units, its reading charged as fuel. + pub(crate) fn sym_name_units(&mut self, k: &Sym) -> JsResult> { + let (units, work) = k.message_name(); + crate::regexp_vm::use_fuel_n(self, work.max(1))?; + Ok(units) + } + + /// [`Sym::message_name`] as text, its reading charged as fuel. + pub(crate) fn sym_name(&mut self, k: &Sym) -> JsResult { + self.sym_name_units(k).map(|u| String::from_utf16_lossy(&u)) + } + + /// `prefix`, the units of `body` and `suffix` as a new string. Flattening `body` and building + /// the string are charged as fuel and checked against the heap limit first. + pub(crate) fn wrap_str(&mut self, prefix: &str, body: Option<&Str>, suffix: &str) -> JsResult { + let body = match body { + Some(b) => crate::string_builtins::flat_charged(self, b)?, + None => Rc::from([]), + }; + let (prefix, suffix): (Vec, Vec) = (prefix.encode_utf16().collect(), suffix.encode_utf16().collect()); + let len = prefix.len().saturating_add(body.len()).saturating_add(suffix.len()); + crate::string_builtins::reserve_units(self, len)?; + let mut units = Vec::with_capacity(len); + units.extend_from_slice(&prefix); + units.extend_from_slice(&body); + units.extend_from_slice(&suffix); + Ok(Value::String(Str::from_units(units))) + } + + /// SymbolDescriptiveString (section 19.4.3.3.1): `Symbol(description)` as a new string. + pub(crate) fn descriptive_string(&mut self, k: &Sym) -> JsResult { + let roots = [Value::Symbol(k.clone())]; + self.rooted(&roots, |i| i.wrap_str("Symbol(", k.description(), ")")) + } + + /// A `TypeError` for a property `k` that cannot be defined, when `throw`; otherwise `false`. + fn reject_sym_bool(&mut self, throw: bool, k: &Sym, why: &str) -> JsResult { + if !throw { + return Ok(false); + } + let name = self.sym_name_units(k)?; + self.reject_bool(true, &name, why) + } + + /// A `TypeError` for a property `k` that cannot be set, when `throw`. + fn reject_sym(&mut self, throw: bool, k: &Sym, why: &str) -> JsResult<()> { + if !throw { + return Ok(()); + } + let name = self.sym_name_units(k)?; + self.reject(true, &name, why) + } + + pub(crate) fn get_own_sym(&self, id: ObjId, k: &Sym) -> JsResult> { + Ok(self.object(id)?.syms.as_ref().and_then(|m| m.get(k)).cloned()) + } + + /// The property `k` found on the object or its prototype chain. + pub(crate) fn find_sym(&self, id: ObjId, k: &Sym) -> JsResult> { + let mut cur = Some(id); + let mut steps = 0usize; + while let Some(o) = cur { + if let Some(p) = self.get_own_sym(o, k)? { + return Ok(Some(p)); + } + cur = self.object(o)?.proto; + steps += 1; + if steps > 1_000_000 { + return Err(crate::interp::Abrupt::Internal("prototype chain too long".into())); + } + } + Ok(None) + } + + /// [[Get]] of `k` starting at `start`, with `receiver` as `this` for a getter. + pub(crate) fn get_sym_from(&mut self, start: ObjId, k: &Sym, receiver: &Value) -> JsResult { + match self.find_sym(start, k)? { + None | Some(Prop::Accessor { get: None, .. }) => Ok(Value::Undefined), + Some(Prop::Data { value, .. }) => Ok(value), + Some(Prop::Accessor { get: Some(g), .. }) => self.call(&Value::Object(g), receiver, &[]), + } + } + + /// `base[k]` for any value. + pub(crate) fn get_value_sym(&mut self, base: &Value, k: &Sym) -> JsResult { + if base.is_nullish() { + let (key, base) = (self.sym_name(k)?, if matches!(base, Value::Null) { "null" } else { "undefined" }); + return Err(self.type_error(&format!("cannot read property '{key}' of {base}"))); + } + let start = self.primitive_proto(base, &[])?; + self.get_sym_from(start, k, base) + } + + /// Adds or replaces an own property directly, keeping the heap estimate. + pub(crate) fn define_sym(&mut self, id: ObjId, k: Sym, prop: Prop) -> JsResult<()> { + let o = self.object_mut(id)?; + if o.syms.get_or_insert_with(Box::default).insert(k, prop) { + self.heap.bytes = self.heap.bytes.saturating_add(PROP_BYTES); + } + Ok(()) + } + + /// The default [[DefineOwnProperty]] (section 9.1.6) for a Symbol key. + pub(crate) fn define_own_sym(&mut self, id: ObjId, k: Sym, desc: &Desc, throw: bool) -> JsResult { + let Some(current) = self.get_own_sym(id, &k)? else { + if !self.object(id)?.extensible { + return self.reject_sym_bool(throw, &k, "the object is not extensible"); + } + let mut roots = vec![Value::Object(id), Value::Symbol(k.clone())]; + roots.extend(desc.value.iter().cloned()); + roots.extend(desc.get.flatten().into_iter().chain(desc.set.flatten()).map(Value::Object)); + self.rooted(&roots, |i| i.reserve_heap(PROP_BYTES))?; + let flags = desc.flags_or(0); + let prop = if desc.is_accessor() { + Prop::Accessor { get: desc.get.flatten(), set: desc.set.flatten(), flags: flags & !WRITABLE } + } else { + Prop::Data { value: desc.value.clone().unwrap_or(Value::Undefined), flags } + }; + self.define_sym(id, k, prop)?; + return Ok(true); + }; + let Some(merged) = merge_desc(¤t, desc) else { return self.reject_sym_bool(throw, &k, "the property cannot be redefined") }; + self.define_sym(id, k, merged)?; + Ok(true) + } + + /// [[Set]] (section 9.1.9) of an ordinary object for a Symbol key. + pub(crate) fn put_sym(&mut self, id: ObjId, k: Sym, v: Value, throw: bool) -> JsResult<()> { + match self.get_own_sym(id, &k)? { + Some(Prop::Data { flags, .. }) => { + if flags & WRITABLE == 0 { + return self.reject_sym(throw, &k, "it is read-only"); + } + if let Some(Some(Prop::Data { value, .. })) = self.object_mut(id)?.syms.as_mut().map(|m| m.get_mut(&k)) { + *value = v; + } + return Ok(()); + } + Some(Prop::Accessor { set: Some(s), .. }) => return self.call(&Value::Object(s), &Value::Object(id), &[v]).map(drop), + Some(Prop::Accessor { set: None, .. }) => return self.reject_sym(throw, &k, "it has only a getter"), + None => {} + } + let proto = self.object(id)?.proto; + match proto.map(|p| self.find_sym(p, &k)).transpose()?.flatten() { + Some(Prop::Accessor { set: Some(s), .. }) => return self.call(&Value::Object(s), &Value::Object(id), &[v]).map(drop), + Some(Prop::Accessor { set: None, .. }) => return self.reject_sym(throw, &k, "it has only a getter"), + Some(Prop::Data { flags, .. }) if flags & WRITABLE == 0 => return self.reject_sym(throw, &k, "it is read-only"), + _ => {} + } + if !self.object(id)?.extensible { + return self.reject_sym(throw, &k, "the object is not extensible"); + } + let roots = [Value::Object(id), Value::Symbol(k.clone()), v.clone()]; + self.rooted(&roots, |i| i.reserve_heap(PROP_BYTES))?; + self.define_sym(id, k, Prop::Data { value: v, flags: crate::heap::OPEN }) + } + + /// PutValue (section 6.2.4.9) on a Symbol-keyed reference, whose base may be a primitive. + pub(crate) fn put_value_sym(&mut self, base: &Value, k: Sym, v: Value) -> JsResult<()> { + match base { + Value::Object(o) => { + let throw = self.strict_writes(); + self.put_sym(*o, k, v, throw) + } + Value::Undefined | Value::Null => { + let (key, base) = (self.sym_name(&k)?, if matches!(base, Value::Null) { "null" } else { "undefined" }); + Err(self.type_error(&format!("cannot set property '{key}' of {base}"))) + } + _ => { + let proto = self.primitive_proto(base, &[])?; + if let Some(Prop::Accessor { set: Some(s), .. }) = self.find_sym(proto, &k)? { + return self.call(&Value::Object(s), base, &[v]).map(drop); + } + let strict = self.strict(); + self.reject_sym(strict, &k, "the value is a primitive") + } + } + } + + /// [[Delete]] (section 9.1.10) for a Symbol key. + pub(crate) fn delete_sym(&mut self, id: ObjId, k: &Sym, throw: bool) -> JsResult { + match self.get_own_sym(id, k)? { + None => Ok(true), + Some(p) if p.configurable() => { + if let Some(m) = self.object_mut(id)?.syms.as_mut() { + m.remove(k); + } + Ok(true) + } + Some(_) if throw => { + let key = self.sym_name(k)?; + Err(self.type_error(&format!("cannot delete property '{key}'"))) + } + Some(_) => Ok(false), + } + } + + /// An object's own Symbol keys in the order they were added. Each takes a unit of fuel, and + /// the heap for the list is checked first. + pub(crate) fn own_symbols(&mut self, id: ObjId) -> JsResult> { + let count = self.object(id)?.syms.as_ref().map_or(0, |m| m.len()); + self.reserve_heap(count.saturating_mul(16))?; + for _ in 0..count { + self.use_fuel()?; + } + Ok(self.object(id)?.syms.iter().flat_map(|m| m.iter()).map(|(k, _)| k.clone()).collect()) + } + + // ---- either kind of key ---- + + pub(crate) fn get_own_pk(&self, id: ObjId, k: &PropKey) -> JsResult> { + match k { + PropKey::Str(name) => self.get_own_property(id, name), + PropKey::Sym(s) => self.get_own_sym(id, s), + } + } + + pub(crate) fn has_pk(&self, id: ObjId, k: &PropKey) -> JsResult { + match k { + PropKey::Str(name) => self.has_property(id, name), + PropKey::Sym(s) => Ok(self.find_sym(id, s)?.is_some()), + } + } + + pub(crate) fn define_own_pk(&mut self, id: ObjId, k: PropKey, desc: &Desc, throw: bool) -> JsResult { + match k { + PropKey::Str(name) => self.define_own_property(id, name, desc, throw), + PropKey::Sym(s) => self.define_own_sym(id, s, desc, throw), + } + } + + pub(crate) fn get_value_pk(&mut self, base: &Value, k: &PropKey) -> JsResult { + match k { + PropKey::Str(name) => self.get_value(base, name), + PropKey::Sym(s) => self.get_value_sym(base, s), + } + } + + pub(crate) fn put_value_pk(&mut self, base: &Value, k: PropKey, v: Value) -> JsResult<()> { + match k { + PropKey::Str(name) => self.put_value(base, name, v), + PropKey::Sym(s) => self.put_value_sym(base, s, v), + } + } + + pub(crate) fn delete_pk(&mut self, id: ObjId, k: &PropKey, throw: bool) -> JsResult { + match k { + PropKey::Str(name) => self.delete(id, name, throw), + PropKey::Sym(s) => self.delete_sym(id, s, throw), + } + } + + // ---- the hooks the well-known Symbols name ---- + + /// The well-known Symbol `pick` chooses, in a realm that has them. + pub(crate) fn well_known(&self, pick: fn(&WellKnown) -> &Sym) -> Option { + self.symbols.well_known.as_ref().map(|w| pick(w).clone()) + } + + /// Steps 2 and 3 of ToPrimitive (section 7.1.1): the result of the object's + /// `@@toPrimitive` method called with the hint, or `None` when it has none. + pub(crate) fn exotic_to_primitive(&mut self, o: ObjId, v: &Value, hint: Hint) -> JsResult> { + let Some(sym) = self.well_known(|w| &w.to_primitive) else { return Ok(None) }; + let f = self.get_sym_from(o, &sym, v)?; + if f.is_nullish() { + return Ok(None); + } + if !self.is_callable(&f) { + return Err(self.type_error("the value is not a function")); + } + let hint = match hint { + Hint::Default => "default", + Hint::Number => "number", + Hint::String => "string", + }; + let r = self.call(&f, v, &[Value::str(hint)])?; + if matches!(r, Value::Object(_)) { + return Err(self.type_error("cannot convert the object to a primitive value")); + } + Ok(Some(r)) + } + + /// Steps 2 to 4 of InstanceofOperator (section 12.10.4): the answer of `f`'s + /// `@@hasInstance` method, or `None` when `f` is not an object or has none. + pub(crate) fn has_instance_hook(&mut self, v: &Value, f: &Value) -> JsResult> { + let Some(sym) = self.well_known(|w| &w.has_instance) else { return Ok(None) }; + let Value::Object(fid) = f else { return Ok(None) }; + let handler = self.get_sym_from(*fid, &sym, f)?; + if handler.is_nullish() { + return Ok(None); + } + if !self.is_callable(&handler) { + return Err(self.type_error("the value is not a function")); + } + Ok(Some(self.call(&handler, f, std::slice::from_ref(v))?.truthy())) + } + + /// For the target of a bound function in OrdinaryHasInstance (section 7.3.21, step 2): the + /// answer of its own `@@hasInstance` method when that is not `Function.prototype`'s, whose + /// answer is the one the caller goes on to give. + pub(crate) fn bound_target_hook(&mut self, v: &Value, target: ObjId) -> JsResult> { + let default = self.symbols.objects.map(|o| o.has_instance); + match self.has_instance_handler(target)? { + Some(h) if Some(h) != default => { + let f = Value::Object(target); + Ok(Some(self.call(&Value::Object(h), &f, std::slice::from_ref(v))?.truthy())) + } + _ => Ok(None), + } + } + + /// `target[@@hasInstance]` when it is callable, `None` when it is absent; anything else + /// throws a `TypeError`. + fn has_instance_handler(&mut self, target: ObjId) -> JsResult> { + let Some(sym) = self.well_known(|w| &w.has_instance) else { return Ok(None) }; + let handler = self.get_sym_from(target, &sym, &Value::Object(target))?; + match handler { + Value::Undefined | Value::Null => Ok(None), + Value::Object(h) if self.is_callable(&handler) => Ok(Some(h)), + _ => Err(self.type_error("the value is not a function")), + } + } + + /// The `@@toStringTag` of `o` when it is a string (section 19.1.3.6, steps 15 and 16). + pub(crate) fn string_tag_of(&mut self, o: ObjId) -> JsResult> { + let Some(sym) = self.well_known(|w| &w.to_string_tag) else { return Ok(None) }; + match self.get_sym_from(o, &sym, &Value::Object(o))? { + Value::String(s) => Ok(Some(s)), + _ => Ok(None), + } + } +} diff --git a/crates/js/src/symbol_tests.rs b/crates/js/src/symbol_tests.rs new file mode 100644 index 0000000000..d877e04106 --- /dev/null +++ b/crates/js/src/symbol_tests.rs @@ -0,0 +1,230 @@ +//! `Symbol`, Symbol-keyed properties and the iterators of arrays, strings and `arguments` +//! objects, in a realm with [`Options::es2015`]. + +use crate::{JsValue, LimitKind, Limits, Options, Realm, RunError, RunErrorKind}; + +fn es2015(limits: Limits) -> Realm { + Realm::with_options(Options { es2015: true, ..Options::default() }, limits) +} + +fn run(src: &str) -> JsValue { + match es2015(Limits::default()).run(src) { + Ok(v) => v, + Err(e) => panic!("{src}\n{e:?}"), + } +} + +fn truth(src: &str) { + assert_eq!(run(src), JsValue::Bool(true), "{src}"); +} + +fn string(src: &str) -> String { + match run(src) { + JsValue::String(s) => s, + other => panic!("{src}: {other:?}"), + } +} + +/// The run throws an error whose message starts with `name`. +fn throws(src: &str, name: &str) { + match es2015(Limits::default()).run(src) { + Err(RunError { kind: RunErrorKind::Thrown, message, .. }) => assert!(message.starts_with(name), "{src}: {message}"), + other => panic!("{src}: {other:?}"), + } +} + +#[test] +fn symbols_are_unique_values_with_a_description() { + truth("typeof Symbol() === 'symbol' && typeof Symbol('a') === 'symbol'"); + truth("Symbol('a') !== Symbol('a') && Symbol('a') != Symbol('a')"); + truth("var s = Symbol('a'); s === s && s == Object(s) && Object(s) == s"); + truth("Symbol('a').description === 'a' && Symbol().description === undefined && Symbol('').description === ''"); + assert_eq!(string("String(Symbol('a b'))"), "Symbol(a b)"); + assert_eq!(string("Symbol().toString()"), "Symbol()"); + truth("var s = Symbol(); Object(s).valueOf() === s && typeof Object(s) === 'object'"); + truth("Object.prototype.toString.call(Symbol()) === '[object Symbol]'"); + truth("!!Symbol() && Symbol.length === 0 && Symbol.prototype.constructor === Symbol"); + throws("new Symbol()", "TypeError"); + throws("Symbol.prototype.toString.call({})", "TypeError"); +} + +#[test] +fn symbol_for_and_key_for_use_the_registry() { + truth("Symbol.for('k') === Symbol.for('k') && Symbol.for('k') !== Symbol('k')"); + truth("Symbol.keyFor(Symbol.for('k')) === 'k' && Symbol.keyFor(Symbol('k')) === undefined"); + truth("Symbol.keyFor(Symbol.iterator) === undefined && Symbol.for('x').description === 'x'"); + throws("Symbol.keyFor('k')", "TypeError"); + throws("Symbol.for(Symbol())", "TypeError"); +} + +#[test] +fn implicit_conversion_of_a_symbol_throws_a_type_error() { + throws("Symbol() + ''", "TypeError"); + throws("'' + Symbol('a')", "TypeError"); + throws("+Symbol()", "TypeError"); + throws("Symbol() * 2", "TypeError"); + throws("Symbol() < 1", "TypeError"); + throws("[Symbol()].join()", "TypeError"); + throws("'abc'.indexOf(Symbol())", "TypeError"); + throws("Symbol(Symbol())", "TypeError"); + throws("new String(Symbol())", "TypeError"); + truth("String(Symbol('x')) === 'Symbol(x)' && Symbol('x').toString() === 'Symbol(x)'"); +} + +#[test] +fn symbol_keys_are_hidden_from_for_in_keys_and_json() { + let setup = "var s = Symbol('s'); var o = {a: 1}; o[s] = 2; "; + truth(&format!("{setup} var n = []; for (var k in o) n.push(k); n.join() === 'a'")); + truth(&format!("{setup} Object.keys(o).join() === 'a' && Object.getOwnPropertyNames(o).join() === 'a'")); + truth(&format!("{setup} JSON.stringify(o) === '{{\"a\":1}}'")); + truth("JSON.stringify({a: Symbol()}) === '{}' && JSON.stringify([Symbol()]) === '[null]' && JSON.stringify(Symbol()) === undefined"); + truth(&format!("{setup} var l = Object.getOwnPropertySymbols(o); l.length === 1 && l[0] === s && o[s] === 2")); + truth(&format!("{setup} s in o && o.hasOwnProperty(s) && o.propertyIsEnumerable(s) && delete o[s] && !(s in o)")); + truth(&format!("{setup} o[Object(s)] === 2 && o[s.toString()] === undefined")); + throws("var w = new String('x'); w.toString = function () { return Symbol(); }; JSON.stringify(w)", "TypeError"); + truth("var o = Object(Symbol()); delete Symbol.prototype[Symbol.toStringTag]; Object.prototype.toString.call(o) === '[object Object]'"); +} + +#[test] +fn define_property_freeze_and_descriptors_take_symbol_keys() { + truth( + "var s = Symbol(); var o = {}; Object.defineProperty(o, s, {value: 1}); \ + var d = Object.getOwnPropertyDescriptor(o, s); d.value === 1 && !d.writable && !d.enumerable && !d.configurable", + ); + truth("var s = Symbol(); var o = {}; o[s] = 1; Object.freeze(o); o[s] = 2; o[s] === 1 && Object.isFrozen(o)"); + truth("var s = Symbol(); var o = {}; o[s] = 1; Object.preventExtensions(o); Object.isSealed(o) === false"); + truth("var s = Symbol(); var p = {}; p[s] = {value: 3, enumerable: true}; var o = Object.create(null, p); o[s] === 3"); + throws("'use strict'; var s = Symbol(); var o = Object.freeze((function () { var x = {}; x[s] = 1; return x; })()); o[s] = 2;", "TypeError"); + truth("var s = Symbol(); var o = {}; o[s] = 1; o[s]++; o[s] === 2"); +} + +#[test] +fn well_known_symbols_hook_the_operations_that_read_them() { + truth("var o = {}; o[Symbol.toStringTag] = 'Thing'; Object.prototype.toString.call(o) === '[object Thing]'"); + truth("var o = {}; o[Symbol.toPrimitive] = function (h) { return h === 'number' ? 7 : 'str'; }; +o === 7 && String(o) === 'str'"); + throws("var o = {}; o[Symbol.toPrimitive] = function () { return {}; }; +o", "TypeError"); + throws("var o = {}; o[Symbol.toPrimitive] = 1; +o", "TypeError"); + truth("var C = {}; C[Symbol.hasInstance] = function (v) { return v === 1; }; (1 instanceof C) && !(2 instanceof C)"); + truth("function F() {} var B = F.bind(); new F() instanceof B && typeof Function.prototype[Symbol.hasInstance] === 'function'"); + truth("Function.prototype[Symbol.hasInstance].call(Array, []) === true && Function.prototype[Symbol.hasInstance].call({}, []) === false"); + truth( + "Symbol.iterator.toString() === 'Symbol(Symbol.iterator)' && typeof Symbol.asyncIterator === 'symbol' \ + && typeof Symbol.hasInstance === 'symbol' && typeof Symbol.toPrimitive === 'symbol' && typeof Symbol.toStringTag === 'symbol'", + ); +} + +#[test] +fn an_array_iterator_driven_by_hand_steps_through_values_keys_and_entries() { + truth( + "var it = [10, 20][Symbol.iterator](); var a = it.next(), b = it.next(), c = it.next(), d = it.next(); \ + a.value === 10 && !a.done && b.value === 20 && !b.done && c.value === undefined && c.done && d.done", + ); + truth("var it = ['a', 'b'].keys(); it.next().value === 0 && it.next().value === 1 && it.next().done"); + truth("var e = ['x'].entries().next().value; e.length === 2 && e[0] === 0 && e[1] === 'x'"); + truth("Array.prototype[Symbol.iterator] === Array.prototype.values"); + truth("var a = [1]; var it = a.values(); it.next(); a.push(2); it.next().value === 2"); + truth("var it = [].values(); it[Symbol.iterator]() === it && Object.prototype.toString.call(it) === '[object Array Iterator]'"); + truth("var it = Array.prototype.values.call({length: 1, 0: 'q'}); it.next().value === 'q'"); + throws("[].values().next.call({})", "TypeError"); + throws("[].values().next.call(''[Symbol.iterator]())", "TypeError"); +} + +#[test] +fn a_string_iterator_steps_by_code_point() { + truth( + "var it = 'a\\uD83D\\uDE00b'[Symbol.iterator](); var x = it.next().value, y = it.next().value, z = it.next().value; \ + x === 'a' && y === '\\uD83D\\uDE00' && y.length === 2 && z === 'b' && it.next().done", + ); + truth("var it = '\\uDE00\\uD83D'[Symbol.iterator](); it.next().value === '\\uDE00' && it.next().value === '\\uD83D' && it.next().done"); + truth("Object.prototype.toString.call(''[Symbol.iterator]()) === '[object String Iterator]'"); + throws("String.prototype[Symbol.iterator].call(null)", "TypeError"); +} + +#[test] +fn arguments_objects_have_the_array_values_iterator() { + truth("(function () { return arguments[Symbol.iterator] === Array.prototype.values; })()"); + truth("(function () { 'use strict'; var it = arguments[Symbol.iterator](); return it.next().value === 5 && it.next().done; })(5)"); + truth("(function () { return !arguments.propertyIsEnumerable(Symbol.iterator); })()"); +} + +#[test] +fn realms_without_es2015_have_no_symbol() { + for options in [Options::default(), Options { e4x: true, preprocessor_lines: true, ..Options::default() }] { + let mut realm = Realm::with_options(options, Limits::default()); + let src = "typeof Symbol === 'undefined' && Array.prototype.values === undefined && Object.getOwnPropertySymbols === undefined"; + assert_eq!(realm.run(src), Ok(JsValue::Bool(true))); + let src = "Object.getOwnPropertyNames((function () { return arguments; })()).join()"; + assert_eq!(realm.run(src), Ok(JsValue::String("length,callee".into()))); + } +} + +#[test] +fn symbols_and_the_registry_count_against_the_heap_limit() { + let limits = || Limits { heap_bytes: 1 << 20, fuel: 50_000_000, ..Limits::default() }; + let mut realm = es2015(limits()); + match realm.run("for (var i = 0; ; i++) Symbol.for('key' + i);") { + Err(RunError { kind: RunErrorKind::Limit(LimitKind::Heap), .. }) => {} + other => panic!("{other:?}"), + } + let mut realm = es2015(limits()); + match realm.run("var keep = []; for (var i = 0; ; i++) keep.push(Symbol('d' + i));") { + Err(RunError { kind: RunErrorKind::Limit(LimitKind::Heap), .. }) => {} + other => panic!("{other:?}"), + } + // Symbols nothing holds are collected, so making them one after another does not fill the + // heap, and keys survive a collection. + let mut realm = es2015(limits()); + let src = "var s = Symbol('k'); var o = {}; o[s] = 'v'; for (var i = 0; i < 40000; i++) Symbol('x' + i); o[s] === 'v'"; + assert_eq!(realm.run(src), Ok(JsValue::Bool(true))); +} + +#[test] +fn an_error_names_a_long_symbol_by_the_start_of_its_description() { + // `d` is a rope of 4,194,304 units whose halves share one node, so it takes little heap until + // something copies it whole. Each error names the Symbol by the first 256 units only. + let setup = "var d = 'x'; for (var i = 0; i < 22; i++) d = d + d; var s = Symbol(d); \ + var shut = Object.preventExtensions({}); var fixed = Object.defineProperty({}, s, { value: 1 }); "; + let named = format!("Symbol({}...)", "x".repeat(256)); + for (attempt, message) in [ + ("shut[s] = 1", format!("cannot assign to property '{named}': the object is not extensible")), + ("Object.defineProperty(shut, s, { value: 1 })", format!("cannot define property '{named}': the object is not extensible")), + ("Object.defineProperty(fixed, s, { value: 2 })", format!("cannot define property '{named}': the property cannot be redefined")), + ("fixed[s] = 2", format!("cannot assign to property '{named}': it is read-only")), + ("delete fixed[s]", format!("cannot delete property '{named}'")), + ("null[s]", "cannot read a property of null".to_string()), + ] { + let src = format!( + "{setup} (function () {{ 'use strict'; try {{ {attempt}; return 'none'; }} catch (e) {{ return (e instanceof TypeError) + ' ' + e.message; }} }})()" + ); + let mut realm = es2015(Limits { heap_bytes: 64 << 20, fuel: 1_000_000, ..Limits::default() }); + assert_eq!(realm.run(&src), Ok(JsValue::String(format!("true {message}"))), "{attempt}"); + } + // A write that does not throw leaves the Symbol's description as it is. + let src = format!("{setup} shut[s] = 1; fixed[s] = 2; shut[s] === undefined && fixed[s] === 1"); + assert_eq!(es2015(Limits { heap_bytes: 64 << 20, fuel: 1_000_000, ..Limits::default() }).run(&src), Ok(JsValue::Bool(true))); +} + +#[test] +fn an_array_iterator_keeps_its_object_while_reading_its_length_runs_script() { + // The `length` getter finishes the iterator by stepping it again, which lets go of `obj`, and + // the length's `valueOf` drops the last reference to `obj`, fills the heap until it collects + // and then reuses every free slot. The step still reads the element of `obj`. + let src = "var obj = { 0: 'x', 1: 'y' }, it = Array.prototype.values.call(obj), calls = 0, junk, fresh = []; \ + Object.defineProperty(obj, 'length', { get: function () { \ + calls++; if (calls > 1) return 0; it.next(); \ + return { valueOf: function () { obj = null; \ + for (var i = 0; i < 60000; i++) junk = { a: i }; \ + for (var j = 0; j < 70000; j++) fresh.push({ 0: 'wrong' }); return 2; } }; } }); 0; \ + var r = it.next(); r.value + ' ' + r.done + ' ' + it.next().done"; + assert_eq!(string(src), "x false true"); +} + +#[test] +fn iterator_steps_take_fuel() { + let mut realm = es2015(Limits { fuel: 5_000, ..Limits::default() }); + let src = "var a = []; a.length = 1e9; var it = a.values(); while (!it.next().done) {}"; + match realm.run(src) { + Err(RunError { kind: RunErrorKind::Limit(LimitKind::Fuel), .. }) => {} + other => panic!("{other:?}"), + } +} diff --git a/crates/js/src/value.rs b/crates/js/src/value.rs index a0fbcd4a53..66005773e2 100644 --- a/crates/js/src/value.rs +++ b/crates/js/src/value.rs @@ -19,6 +19,9 @@ pub(crate) enum Value { Number(f64), String(Str), Object(ObjId), + /// A Symbol (ECMA-262 11th edition, section 6.1.5), which only a realm with + /// [`crate::Options::es2015`] makes. + Symbol(crate::symbol::Sym), } impl Value { @@ -44,7 +47,7 @@ impl Value { Value::Bool(b) => *b, Value::Number(n) => !(n.is_nan() || *n == 0.0), Value::String(s) => s.len() > 0, - Value::Object(_) => true, + Value::Object(_) | Value::Symbol(_) => true, } } } @@ -191,6 +194,30 @@ impl Str { } } + /// At most `max` code units from the start, read along the rope without flattening it, + /// visiting at most `max_nodes` nodes, with the number of nodes visited. When the nodes run + /// out first, the units read so far are returned. + pub(crate) fn prefix(&self, max: usize, max_nodes: u64) -> (Vec, u64) { + let mut units = Vec::new(); + let mut stack = vec![self.clone()]; + let mut visited = 0u64; + while let Some(node) = stack.pop() { + if units.len() >= max || visited >= max_nodes { + break; + } + visited += 1; + match &*node.0.borrow() { + Node::Flat(f) => units.extend_from_slice(f.get(..f.len().min(max - units.len())).unwrap_or_default()), + Node::Concat { left, right, .. } => { + stack.push(right.clone()); + stack.push(left.clone()); + } + Node::Taken => {} + } + } + (units, visited) + } + pub(crate) fn to_rust_string(&self) -> String { String::from_utf16_lossy(&self.flat()) } diff --git a/crates/js/tests/test262.rs b/crates/js/tests/test262.rs index 23337128bb..aeee6ca692 100644 --- a/crates/js/tests/test262.rs +++ b/crates/js/tests/test262.rs @@ -35,6 +35,11 @@ //! `annexb-language-failures.txt` and `annexb-builtins-failures.txt`). A suite without //! `test/annexB/` skips them; a folder there with no test to parse or run fails them. //! +//! Another test runs the tests of `Symbol`, `Object.getOwnPropertySymbols` and the iterators of +//! arrays and strings (the folders [`SYMBOL_BUILT_INS`] names) in a realm with +//! [`Options::es2015`]: tests of any edition whose feature tags are all in [`SYMBOL_FEATURES`] and +//! that parse as ES5. Its failures go to `symbol-failures.txt`. +//! //! The runner reads only regular files inside the suite: it does not follow symbolic links, refuses //! an `includes:` name that leaves the `harness/` folder, and refuses a file over //! [`MAX_FILE_BYTES`] before reading it. A folder or file it cannot read fails the test. @@ -444,7 +449,12 @@ fn runs_strings_as_code(tokens: &[Token]) -> bool { /// Runs one test in a new realm; `Err` describes a failure. fn run_one(script: &str, negative_type: Option<&str>) -> Result<(), String> { - let mut realm = Realm::with_options(Options::default(), Limits { fuel: 20_000_000, heap_bytes: 256 << 20, ..Limits::default() }); + run_one_with(&Options::default(), script, negative_type) +} + +/// Runs one test in a new realm made with `options`; `Err` describes a failure. +fn run_one_with(options: &Options, script: &str, negative_type: Option<&str>) -> Result<(), String> { + let mut realm = Realm::with_options(options.clone(), Limits { fuel: 20_000_000, heap_bytes: 256 << 20, ..Limits::default() }); match (realm.run(script), negative_type) { (Ok(_), None) => Ok(()), (Ok(_), Some(t)) => Err(format!("completed; a {t} was expected")), @@ -696,6 +706,110 @@ fn run_annex_b(dir: &Path) { assert_eq!(panicked, 0, "the interpreter panicked; see the Annex B failure files in {}", dir.display()); } +/// The folders of the tests of `Symbol`, Symbol-keyed properties and the iterators of arrays and +/// strings, which run in a realm with [`Options::es2015`]. +const SYMBOL_BUILT_INS: &[&str] = &[ + "built-ins/Symbol", + "built-ins/ArrayIteratorPrototype", + "built-ins/StringIteratorPrototype", + "built-ins/Object/getOwnPropertySymbols", + "built-ins/Array/prototype/values", + "built-ins/Array/prototype/keys", + "built-ins/Array/prototype/entries", + "built-ins/Array/prototype/Symbol.iterator", + "built-ins/String/prototype/Symbol.iterator", +]; + +/// The feature tags of the tests under [`SYMBOL_BUILT_INS`] that run; a test with any other tag is +/// skipped. +const SYMBOL_FEATURES: &[&str] = &[ + "Symbol", + "Symbol.iterator", + "Symbol.toStringTag", + "Symbol.hasInstance", + "Symbol.toPrimitive", + "Symbol.asyncIterator", + "Symbol.prototype.description", +]; + +#[test] +fn es2015_symbol_and_iterators_run() { + let Some(dir) = suite_dir() else { + println!("test262 Symbol and iterators: SKIPPED (no suite; run cargo xtask test262)"); + return; + }; + let handle = std::thread::Builder::new().stack_size(64 << 20).spawn(move || run_symbol_built_ins(&dir)).unwrap(); + handle.join().unwrap(); +} + +/// Runs the tests under each folder [`SYMBOL_BUILT_INS`] names in a realm with +/// [`Options::es2015`], prints the counts of each and writes the failures to +/// `symbol-failures.txt` beside the suite. +fn run_symbol_built_ins(dir: &Path) { + let options = Options { es2015: true, ..Options::default() }; + let missing: HashSet<&str> = missing_builtins(&[TEXT_BUILTINS, "Symbol"]); + let mut all = RunCounts::default(); + let mut report = String::new(); + for folder in SYMBOL_BUILT_INS { + let root = or_fail(inside(dir, &format!("test/{folder}"))); + assert!(root.is_dir(), "{} is not a test262 checkout", dir.display()); + let counts = run_tagged_tests(dir, &root, &missing, &options, SYMBOL_FEATURES); + println!("test262 {folder} with Options::es2015: {}.", counts.summary()); + report.push_str(&format!("# {folder}\n{}\n", counts.failures)); + all.add(counts); + } + assert!(all.tests > 0, "no Symbol or iterator tests ran under {}", dir.display()); + let path = dir.join("symbol-failures.txt"); + if let Err(e) = std::fs::write(&path, &report) { + println!("could not write {}: {e}", path.display()); + } + println!("test262 Symbol and iterators with Options::es2015: {}. Failures: {}", all.summary(), path.display()); + assert_eq!(all.panicked, 0, "the interpreter panicked; see {}", path.display()); +} + +/// Runs the script tests under `root` of any edition whose feature tags are all in `features`, +/// each in a new realm made with `options` after the harness, the way [`run_tests`] runs the +/// others. A test with another tag is counted as skipped. +fn run_tagged_tests(dir: &Path, root: &Path, missing: &HashSet<&str>, options: &Options, features: &[&str]) -> RunCounts { + let harness = |name: &str| or_fail(inside(dir, &format!("harness/{name}")).and_then(|p| read_source(&p))); + let prelude = format!("{}\n{}\n", harness("assert.js"), harness("sta.js")); + let mut counts = RunCounts::default(); + for path in or_fail(test_files(root)) { + let source = or_fail(read_source(&path)); + let meta = meta(&source); + if meta.flags.iter().any(|f| f == "module") || matches!(meta.negative_phase.as_deref(), Some("parse" | "resolution")) { + continue; + } + let tagged_elsewhere = meta.features.iter().any(|f| !features.contains(&f.as_str())); + let includes: String = meta.includes.iter().map(|i| harness(i) + "\n").collect(); + if tagged_elsewhere || meta.flags.iter().any(|f| f == "async") || needs_missing_builtin(&[&source, &includes], missing) { + counts.skipped += 1; + continue; + } + counts.tests += 1; + let rel = path.strip_prefix(dir).unwrap_or(&path).display().to_string().replace('\\', "/"); + for &strict in modes(&meta) { + let mode = if strict { "strict" } else { "sloppy" }; + let body = if meta.flags.iter().any(|f| f == "raw") { source.clone() } else { format!("{prelude}{includes}{source}") }; + let script = if strict { format!("\"use strict\";\n{body}") } else { body }; + let negative_type = meta.negative_type.clone().filter(|_| meta.negative_phase.as_deref() == Some("runtime")); + match std::panic::catch_unwind(|| run_one_with(options, &script, negative_type.as_deref())) { + Ok(Ok(())) => counts.passed += 1, + Ok(Err(why)) => { + counts.failed += 1; + counts.failures.push_str(&format!("{rel} ({mode}): {why}\n")); + } + Err(_) => { + counts.failed += 1; + counts.panicked += 1; + counts.failures.push_str(&format!("{rel} ({mode}): PANIC\n")); + } + } + } + } + counts +} + /// `needs_missing_builtin` with `Map`, `Symbol` and `Set` missing. fn skips(sources: &[&str]) -> bool { let missing: HashSet<&str> = ["Map", "Symbol", "Set"].into_iter().collect(); diff --git a/docs/mcp.md b/docs/mcp.md index 3c577e0356..9f6b452ea2 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2644,6 +2644,10 @@ app through the global object `vc`, and writes to the Script Console and runs ot - `vc.args` gives a read-only copy of the `args` object each time it is read. - `vc.api.version` is `"1.0"`, and `vc.api.has(feature)` says whether the API has a feature. +A script does not have `Symbol` or the iterators of arrays, strings and `arguments` objects: `typeof Symbol` is +`"undefined"`, and `Array.prototype.values`, `keys` and `entries` are not defined. The JavaScript engine's ECMAScript +2015 mode (`Options::es2015` in `vectorcraft-js`) adds them, as `docs/target-app-parity.md` describes. + Before any of the script runs, its preprocessor lines are read. The help page https://extendscript.docsforadobe.dev/extendscript-tools-features/preprocessor-directives/ describes these lines, and https://extendscript.docsforadobe.dev/extendscript-tools-features/dollar-object/ describes `$.evalFile`, `$.fileName` diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 3da663c191..3264973bf5 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1082,6 +1082,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - `vectorcraft-js` provides the ECMAScript 5.1 built-ins `Object` with its property-descriptor functions, `create`, `keys`, `seal` and `freeze` (section 15.2), `Function.prototype.bind` (15.3.4.5), `Array` with every ES5 method (15.4), the error types (15.11), `Math` (15.8), `JSON` with revivers, replacers and indentation (15.12), and the global functions with Annex B's `escape` and `unescape` (15.1, B.2). The array methods work on array-like objects. A method visits only the indices that exist when its range is longer than 4,096 indices and more than 8 times the properties on the object and its prototypes, so `new Array(4294967295).join("")` ends at once; a shorter range is visited index by index, holes included, and each index takes fuel. `join` writes a cycle back to an array as an empty string, `JSON.stringify` throws a `TypeError` on a cycle, and deep `JSON` nesting uses no native stack. Every loop takes fuel and every result is checked against the heap limit. `cargo xtask test262` runs the suite's ES5 built-in tests that need only these built-ins: 6,798 of 6,866 runs pass (the 34 failing tests expect rules of later editions). It also fetches the `json2.js` polyfill at a pinned commit and checks that its `stringify` and `parse` agree with the built-in `JSON`. Tests: `crates/js/src/builtins_tests.rs`, `crates/js/tests/test262.rs`, `crates/js/tests/json2.rs`. - `vectorcraft-js` has `String`, `Number`, `RegExp` and `Date` as ECMAScript 5.1 defines them (sections 15.5, 15.7, 15.9 and 15.10, https://262.ecma-international.org/5.1/), with Annex B's `substr`, `getYear`, `setYear` and `toGMTString`. `toFixed`, `toExponential` and `toPrecision` format a number from its exact decimal value, and `toString(radix)` writes any base from 2 to 36. Regular expressions (flags `g`, `i` and `m`) run on a backtracking matcher whose choice points and capture state count against the heap limit and which takes fuel for every step, so a catastrophic pattern stops at the fuel limit and 50,000 nested groups give a `SyntaxError` at the default depth limit. A string method that would build a string past the heap limit stops before it allocates. `Date` reads the clock and time zone the host sets (`Realm::set_clock`, `Realm::set_time_zone`; local time is UTC by default). `cargo xtask test262` runs the suite's `built-ins` tests for the four (https://github.com/tc39/test262): of the runs of the ES5 tests that need only the built-ins present, 1,379 of 1,411 pass for `String`, 298 of 298 for `Number`, 954 of 988 for `RegExp` and 8 of 8 for `Date`. The others expect later editions' rules (built-in functions whose `length` can be deleted, flags given with a RegExp object, a negative `lastIndex`, `RegExp.prototype` as a plain object, and `RegExp.prototype`'s `global`, `ignoreCase` and `multiline` properties that can be deleted). Tests: `crates/js/src/text_tests.rs`, `crates/js/tests/test262.rs`. - `cargo xtask test262` also reads the suite's Annex B tests (https://tc39.es/ecma262/#sec-additional-ecmascript-features-for-web-browsers), whichever edition they name. It parses the 819 tests under `test/annexB/language` without a feature tag in the modes their flags give, so a `for`-`in` variable with an initializer must parse in sloppy code and give a `SyntaxError` in strict code (682 of 843 runs pass), and it runs those tests and the `test/annexB/built-ins` tests for `String`, `Date`, `RegExp` and `Function` that need only the built-ins present (263 of 667 runs pass for the language tests and 56 of 252 for the built-ins). Failures go to `annexb-parse-failures.txt`, `annexb-language-failures.txt` and `annexb-builtins-failures.txt` beside the suite. A conformance failure does not fail the tests, but an interpreter panic fails `annex_b_runs`, so `cargo xtask test262` exits non-zero. A folder or file the runner cannot read also fails the test that reads it. The runner reads only regular files inside the suite, up to 8 MiB each, and does not follow symbolic links. Tests: `crates/js/tests/test262.rs`. + - With `Options::es2015` set, which it is not by default, a `vectorcraft-js` realm also has `Symbol` (ECMA-262 11th edition, section 19.4, https://262.ecma-international.org/11.0/): `Symbol(description)`, which `new` refuses with a `TypeError`, the `description` getter, `toString`, `valueOf`, and `Symbol.for` and `Symbol.keyFor` over a registry that lasts as long as the realm. `typeof` gives `"symbol"`. Symbols are property keys: `Object.getOwnPropertySymbols` lists an object's Symbol keys in the order they were added, `Object.defineProperty`, `getOwnPropertyDescriptor`, `freeze`, `seal`, `in`, `delete` and `hasOwnProperty` take them, and `for`-`in`, `Object.keys`, `Object.getOwnPropertyNames` and `JSON.stringify` leave them out. `String(symbol)` and `symbol.toString()` give `Symbol(description)`; any other conversion of a Symbol to a string or a number, such as `Symbol() + ''`, throws a `TypeError`. The well-known Symbols `Symbol.iterator`, `Symbol.asyncIterator`, `Symbol.hasInstance`, `Symbol.toPrimitive` and `Symbol.toStringTag` are defined: conversion to a primitive calls an object's `@@toPrimitive` method, `instanceof` calls the right side's `@@hasInstance` method, and `Object.prototype.toString` writes a string `@@toStringTag`. Nothing reads `Symbol.asyncIterator` yet. `Array.prototype.values` (also `Array.prototype[Symbol.iterator]`), `keys` and `entries`, `String.prototype[Symbol.iterator]` and every `arguments` object's `Symbol.iterator` return iterators whose `next()` gives `{value, done}` objects; a string iterator steps by code point and keeps a surrogate pair together. An array iterator reads the `length` at each step, so it visits elements added during the walk. Each step takes fuel, and each Symbol and registry entry counts against the heap limit. A realm without the option, including the one the app runs scripts in, has none of these names. The language does not have `for`-`of`, spread or destructuring yet, so scripts call `next()` themselves. `cargo xtask test262` runs the suite's tests of `Symbol`, `ArrayIteratorPrototype`, `StringIteratorPrototype`, `Object.getOwnPropertySymbols`, `Array.prototype.values`, `keys`, `entries` and `Symbol.iterator`, and `String.prototype[Symbol.iterator]` that need only these built-ins and parse as ES5, in such a realm: 164 of 216 runs pass (6 passed before), and the 52 others expect a configurable function `length` and a function `name` property. Tests: `crates/js/src/symbol_tests.rs`, `crates/js/tests/test262.rs`. - Scripts: `cargo xtask corpus --scripts` fetches 397 public scripts and 1 file they include from 19 MIT and Apache-2.0 repositories at pinned commits into `corpus/scripts` (gitignored), each repository's license file beside its scripts. `xtask/script-corpus.txt` lists every file with its size and SHA-256, and a download is checked against both before it replaces anything; one more candidate is left out because it is over the 1 MiB limit for one script. `cargo xtask scripts --pass-rate [--report ]` runs each script headless in a process of its own (a new document, 5,000,000 instructions, no dialog answers, file reads only in its repository's folder and a new folder of its own, file writes only in that folder, no command it can start, stopped after 10 seconds) and writes a JSON report: the pass rate overall, per repository and for the scripts without dialogs or windows, how many parse, and each script's outcome. Script failures never fail the command, and without the corpus it skips. These limits are VectorCraft's own. Tests: `xtask/src/script_corpus.rs`, `crates/engine/tests/script_corpus.rs`. - With `Options::e4x` set, an E4X name standing alone (`@a`, `@ns::a`, `@[expr]`, `ns::a`, `*`) inside `with` or a filter predicate can be assigned, with `=` or a compound operator, incremented, decremented, deleted and used as a `for` or `for each` variable, as well as read. Each of these uses the nearest XML or XMLList value in scope that holds the name and evaluates the name once. When no XML value in scope holds the name, the read or write throws a `ReferenceError` before the right-hand side runs and creates no child or attribute, as ECMA-357 section 11.1 (https://ecma-international.org/publications-and-standards/standards/ecma-357/) specifies, so a filter such as `list.(@id == '1')` throws when an item has no `@id` and no outer XML value holds one. Tests: `crates/js/src/xml_tests.rs`. - `vectorcraft-js` runs ECMAScript for XML (ECMA-357, 2nd edition, https://ecma-international.org/publications-and-standards/standards/ecma-357/) when `Options::e4x` is set, which it is not by default: XML and XMLList literals with embedded `{}` expressions, the `..`, `.@`, `.*`, `.()` and `::` selectors, assignment and `delete` on selected nodes, `for each`, `default xml namespace`, and the `XML`, `XMLList`, `Namespace` and `QName` objects with their methods and settings. `xml.xpath(expression[, variables])` evaluates an XPath 1.0 expression (https://www.w3.org/TR/1999/REC-xpath-19991116/) with all 13 axes and the 27 core functions, and returns the selected nodes as an XMLList in document order without repeats. Each property of `variables` binds the variable of its name, an XMLList runs the expression on each of its elements in turn, and a prefix in a name test resolves through the context element's in-scope namespaces. An expression that breaks the grammar gives a `SyntaxError`; an unknown function, a wrong argument count, an unbound prefix or variable, and a result that is not a node-set or that holds the root or a namespace node give a `TypeError`. `id()` selects nothing, and evaluation uses no native stack, takes fuel and counts against the heap limit. `` in an XML string gives a `SyntaxError`. An XML declaration at the start of an XML string, after optional white space, is checked against XML 1.0's grammar (https://www.w3.org/TR/xml/#NT-XMLDecl): a version of `1.` and digits, then an optional encoding name and an optional standalone `yes` or `no`, in that order; any other declaration, or one with a character XML does not allow, gives a `SyntaxError`. The parser takes fuel for the length of every name, white space run and declaration it scans, and for the text it searched when a quote, CDATA section, comment or processing instruction is not closed. Parsing, serializing, comparing and copying trees use no native stack, and each takes fuel and counts against the heap limit. Inserting a node into itself or its descendants throws a `TypeError` before the tree changes, a literal or XML string nested past `Options::max_depth` gives a `SyntaxError`, and a tree built past that depth stops at the heap limit. Tests: `crates/js/src/xml_tests.rs`. From 5cd7f7f849c8039729d497a159c228d3cf912a6b Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 22 Nov 2026 01:11:00 -0800 Subject: [PATCH 048/151] Save for Web: Save Color Table writes the whole image's table with no slice selected With slices set to Selected and no slice selected, Save Color Table failed with "no selected slice in the image" although the dialog's preview shows the whole image's table. Without a `slice` parameter the command no longer looks up the slices; a `slice` is still looked up among the slices `slices` names. The preview is unchanged. Docs: docs/mcp.md. --- crates/engine/src/cmd/webexport.rs | 27 ++++++++++++++++++--------- crates/engine/src/tests/webexport.rs | 23 +++++++++++++++++++++++ docs/mcp.md | 4 +++- 3 files changed, 44 insertions(+), 10 deletions(-) diff --git a/crates/engine/src/cmd/webexport.rs b/crates/engine/src/cmd/webexport.rs index 0f77411cd8..8483d7d1ca 100644 --- a/crates/engine/src/cmd/webexport.rs +++ b/crates/engine/src/cmd/webexport.rs @@ -50,7 +50,7 @@ pub fn specs() -> Vec { "Save Color Table", [], None, - "{path?: the .act file (.act is added to a name without an extension), …the settings of document.exportForWeb (preset?, format?: gif|png8…), slice?: n (1-based, from slice.list; default the whole image)} write the GIF or PNG-8 color table the preview shows as a color table file: 772 bytes, the colors as written (red, green, blue) in file order, zero bytes up to 256 colors, then the number of colors and the transparent entry's index (65535 for none), two bytes each, most significant byte first → {path, colors (how many), transparentIndex (null for none), bytes, warnings}; no path → {dataBase64, colors, transparentIndex, bytes, warnings}. jpg and png24 are an error; the document and the settings do not change", + "{path?: the .act file (.act is added to a name without an extension), …the settings of document.exportForWeb (preset?, format?: gif|png8…), slice?: n (1-based, from slice.list, among the slices `slices` names; default the whole image, whatever `slices` is)} write the GIF or PNG-8 color table the preview shows as a color table file: 772 bytes, the colors as written (red, green, blue) in file order, zero bytes up to 256 colors, then the number of colors and the transparent entry's index (65535 for none), two bytes each, most significant byte first → {path, colors (how many), transparentIndex (null for none), bytes, warnings}; no path → {dataBase64, colors, transparentIndex, bytes, warnings}. jpg and png24 are an error; the document and the settings do not change", has_doc, save_color_table ), @@ -1214,7 +1214,7 @@ fn preview(s: &mut Session, p: &Value) -> Result { if !(kbps.is_finite() && kbps > 0.0) { return Err(bad(P, format!("kbps must be a positive number, not {kbps}"))); } - let Shown { o, images, warnings } = shown(s, &settings, p, P)?; + let Shown { o, images, warnings } = shown(s, &settings, p, P, true)?; let mut out = json!({ "format": settings.format.id(), "width": o.width, "height": o.height, "bytes": o.bytes.len(), "seconds": download_seconds(o.bytes.len(), kbps), "kbps": kbps, "slices": images, "warnings": warnings, @@ -1241,7 +1241,7 @@ fn preview(s: &mut Session, p: &Value) -> Result { /// The file Save writes with some settings, as the preview shows it. struct Shown { o: Optimized, - /// The images an export writes. + /// The images an export writes (0 when they were not counted). images: usize, /// The export's warnings. warnings: Vec<&'static str>, @@ -1249,8 +1249,9 @@ struct Shown { /// What Save writes with `settings` for the whole image, or for the slice `p.slice` names (1-based, /// from `slice.list`), for the command `cmd`. A `slice` that is not a whole number from 1 up is an -/// error. -fn shown(s: &mut Session, settings: &WebSettings, p: &Value, cmd: &str) -> Result { +/// error. With `count_images` false and no `slice`, the slices are not looked up: `images` is 0, +/// and selected slices with none selected are not an error. +fn shown(s: &mut Session, settings: &WebSettings, p: &Value, cmd: &str, count_images: bool) -> Result { let slice = match p.get("slice") { None | Some(Value::Null) => None, Some(v) => Some(v.as_u64().filter(|n| *n >= 1).ok_or_else(|| bad(cmd, "`slice` is a slice number from `slice.list`"))?), @@ -1261,9 +1262,17 @@ fn shown(s: &mut Session, settings: &WebSettings, p: &Value, cmd: &str) -> Resul let r = render(doc, settings).map_err(|e| bad(cmd, e))?; let warnings = undecoded(failed); let areas = doc.slice_layout(); - let selected = super::slices::selected_slices(doc, &st.selection); - let cells = cells(&areas, &selected, settings, &r).map_err(|e| bad(cmd, e))?; - let images = cells.iter().filter(|c| c.area.id.and_then(|id| doc.slice_options(id)).is_none_or(|o| o.kind == SliceKind::Image)).count().max(1); + let cells = if count_images || slice.is_some() { + let selected = super::slices::selected_slices(doc, &st.selection); + cells(&areas, &selected, settings, &r).map_err(|e| bad(cmd, e))? + } else { + vec![] + }; + let images = if count_images { + cells.iter().filter(|c| c.area.id.and_then(|id| doc.slice_options(id)).is_none_or(|o| o.kind == SliceKind::Image)).count().max(1) + } else { + 0 + }; let o = match slice { Some(n) => { let c = @@ -1371,7 +1380,7 @@ fn save_color_table(s: &mut Session, p: &Value) -> Result { let path = text_param(p, "path", P)? .filter(|p| !p.trim().is_empty()) .map(|p| if std::path::Path::new(p).extension().is_none() { format!("{p}.{COLOR_TABLE_EXT}") } else { p.to_string() }); - let Shown { o, warnings, .. } = shown(s, &settings, p, P)?; + let Shown { o, warnings, .. } = shown(s, &settings, p, P, false)?; let bytes = act_bytes(&o.colors); let mut out = json!({ "colors": o.colors.len().min(256), diff --git a/crates/engine/src/tests/webexport.rs b/crates/engine/src/tests/webexport.rs index 150ea1f67a..318acad11e 100644 --- a/crates/engine/src/tests/webexport.rs +++ b/crates/engine/src/tests/webexport.rs @@ -1101,6 +1101,29 @@ fn save_color_table_writes_the_path_and_refuses_bad_params() { let _ = std::fs::remove_dir_all(dir); } +/// With Save for Web set to the selected slices and none selected, Save Color Table still writes +/// the whole image's table, the one the dialog's preview shows. A `slice` is still looked up among +/// the selected slices. +#[test] +fn save_color_table_of_the_whole_image_needs_no_selected_slice() { + let mut s = two_colours(); + let slice = run(&mut s, "object.slice.create", json!({"x": 0, "y": 0, "width": 20, "height": 30}))["id"].as_u64().unwrap(); + run(&mut s, "object.slice.select", json!({})); + let p = json!({"format": "gif", "dither": "none", "transparency": false}); + let (_, whole) = color_table_file(&mut s, merge(&p, json!({"slices": "none"}))); + let (v, bytes) = color_table_file(&mut s, merge(&p, json!({"slices": "selected"}))); + assert_eq!(bytes, whole, "{v}"); + let number = run(&mut s, "slice.list", json!({}))["slices"] + .as_array() + .unwrap() + .iter() + .find(|l| l["id"].as_u64() == Some(slice)) + .map(|l| l["number"].clone()) + .unwrap(); + let e = s.execute("document.exportForWeb.saveColorTable", &merge(&p, json!({"slices": "selected", "slice": number}))).unwrap_err().to_string(); + assert!(e.contains("no selected slice"), "{e}"); +} + /// The preview refuses a `slice` that is not a slice number instead of previewing the whole image. #[test] fn preview_refuses_a_slice_that_is_not_a_number() { diff --git a/docs/mcp.md b/docs/mcp.md index 29b05a8090..a037c2b25b 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -10573,7 +10573,9 @@ the GIF or PNG-8 color table the preview shows as a color table file (`.act`) in specification gives (https://www.adobe.com/devnet-apps/photoshop/fileformatashtml/): 256 entries of three bytes (red, green, blue) in file order, with zero bytes after the colors used, then the number of colors used and the index of the transparent entry, two bytes each with the most significant byte first. The file is always 772 bytes, and the index is -65535 when the table has no transparent entry. A color shifted by hand is written as its new color. `.act` is added to +65535 when the table has no transparent entry. A color shifted by hand is written as its new color. Without `slice` +the file holds the whole image's table, also when `slices` is `selected` and no slice is selected; a `slice` is looked +up among the slices `slices` names. `.act` is added to a `path` without an extension, and without `path` the file comes back as `dataBase64`. The reply is `{path, colors, transparentIndex, bytes, warnings}` (`transparentIndex` is null when there is none). JPEG and PNG-24 are errors, and the document and the settings do not change. Load Color Table… is `webExport.loadColorTable {path | dataBase64, From b88f48fd92c461fc517146dae5a8d041ebb0a0cc Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 22 Nov 2026 01:19:33 -0800 Subject: [PATCH 049/151] Quick Pen: a segment drag from its selected ends selects the segment A drag on a segment whose two ends were already selected as anchors kept that anchor selection, so Delete afterwards removed both anchors instead of cutting the connection. The drag now keeps the current selection only when that segment alone is selected; otherwise it selects the segment with select.segments, as it does from a path selected whole. --- crates/engine/src/tests/quickpen.rs | 22 ++++++++++++++++++++++ crates/tools/src/quickpen/edit.rs | 6 ++++-- 2 files changed, 26 insertions(+), 2 deletions(-) diff --git a/crates/engine/src/tests/quickpen.rs b/crates/engine/src/tests/quickpen.rs index e9c8970e00..7d15e67609 100644 --- a/crates/engine/src/tests/quickpen.rs +++ b/crates/engine/src/tests/quickpen.rs @@ -1135,6 +1135,28 @@ fn a_segment_drag_moves_only_its_ends() { assert_eq!(paths(&s).len(), 1); } +/// A drag on a segment whose two ends are already selected as anchors selects the segment, so +/// Delete then cuts that connection and keeps both anchors. +#[test] +fn a_segment_drag_from_its_selected_ends_selects_the_segment() { + let mut s = session(); + let pieces = json!([{"x": 200, "y": 100}, {"x": 300, "y": 100}, {"x": 400, "y": 100}]); + let id = selected_quick_pen_path(&mut s, (100.0, 100.0), pieces); + click(&mut s, 200.0, 100.0); + shift_click(&mut s, 300.0, 100.0); + let picked = s.doc().unwrap().selection.partial(id).cloned().unwrap_or_default().into_iter().collect::>(); + assert_eq!(picked, [(0, 1), (0, 2)]); + press(&mut s, &[(250.0, 100.0), (250.0, 120.0), (250.0, 150.0)]); + assert_eq!(points(&s), [pt(100.0, 100.0), pt(200.0, 150.0), pt(300.0, 150.0), pt(400.0, 100.0)]); + let segments = s.doc().unwrap().selection.segments.get(&id).cloned().unwrap_or_default().into_iter().collect::>(); + assert_eq!(segments, [(0, 1)], "the segment is selected"); + s.execute("edit.clear", &json!({})).unwrap(); + let left: Vec = paths(&s).iter().flat_map(|(_, pd)| pd.subpaths.iter().flat_map(|sp| sp.anchors.iter().map(|a| a.p))).collect(); + for p in [pt(100.0, 100.0), pt(200.0, 150.0), pt(300.0, 150.0), pt(400.0, 100.0)] { + assert!(left.contains(&p), "{p:?} stays: {left:?}"); + } +} + /// A click on an open end of another path, in front of the selected path, that lies on a segment /// of the selected path goes on drawing from that end. #[test] diff --git a/crates/tools/src/quickpen/edit.rs b/crates/tools/src/quickpen/edit.rs index 2620118b91..e06680d282 100644 --- a/crates/tools/src/quickpen/edit.rs +++ b/crates/tools/src/quickpen/edit.rs @@ -162,13 +162,15 @@ impl Edit { } let Some(picked) = self.grab.anchors(cx) else { return out }; // A drag on one of several selected anchors moves them all; a drag on a segment moves - // its two ends alone. + // its two ends alone and leaves that segment selected, not its ends as anchors. let already = match self.grab { Grab::Anchor { .. } => cx.selection.partial(id).is_some_and(|s| picked.iter().all(|a| s.contains(a))), - Grab::Segment { .. } => { + Grab::Segment { si, seg, .. } => { cx.selection.objects == [id] && cx.selection.anchors.len() == 1 && cx.selection.partial(id).is_some_and(|s| s.len() == picked.len() && picked.iter().all(|a| s.contains(a))) + && cx.selection.segments.len() == 1 + && cx.selection.segments.get(&id).is_some_and(|s| s.len() == 1 && s.contains(&(si, seg))) } }; let moving = if already { From c021b269e7fd3ffff564c8b9b2a7414a63afc6af Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 22 Nov 2026 01:24:03 -0800 Subject: [PATCH 050/151] JavaScript: tighten Symbol conversions, lookups and host crossings in ES2015 realms - A string in `0b` or `0o` form converts to a number in a realm with `Options::es2015`, so an array iterator over an object whose length is "0b10" visits two elements. Realms without the option still read such strings as NaN. - `JSON.stringify` calls a String or Number object's `@@toPrimitive` method before using its stored value, for the value itself, a replacer list entry and the `space` argument. - A host function that returns a Symbol in a realm without the option throws a `TypeError`. A Symbol's description is charged to the heap before it is built. - A text function takes a Symbol as `String(symbol)` gives it, and a data function refuses an object or array with an enumerable Symbol-keyed property; checking the keys takes fuel. - A Symbol-keyed lookup takes a unit of fuel for each prototype it passes, and removing most of an object's Symbol keys releases their storage. --- crates/js/src/builtins/json.rs | 8 ++++- crates/js/src/chars.rs | 2 +- crates/js/src/host.rs | 17 ++++++++- crates/js/src/host_tests.rs | 39 +++++++++++++++++++++ crates/js/src/interp.rs | 32 +++++++++++------ crates/js/src/lib.rs | 10 +++--- crates/js/src/realm.rs | 3 +- crates/js/src/symbol.rs | 32 +++++++++++++++-- crates/js/src/symbol_tests.rs | 64 ++++++++++++++++++++++++++++++++++ crates/js/src/value.rs | 37 ++++++++++++++++---- docs/target-app-parity.md | 2 +- 11 files changed, 217 insertions(+), 29 deletions(-) diff --git a/crates/js/src/builtins/json.rs b/crates/js/src/builtins/json.rs index 6f659922b2..6fc8544e9d 100644 --- a/crates/js/src/builtins/json.rs +++ b/crates/js/src/builtins/json.rs @@ -570,6 +570,8 @@ fn resolve_rooted(interp: &mut Interp, settings: &Settings, holder: ObjId, k: &K /// result is the object's [[PrimitiveValue]] (sections 8.6.2 and 9.9), the value that /// `Number.prototype.valueOf` (15.7.4.4), `Number.prototype.toString` (15.7.4.2) and /// `String.prototype.toString` (15.5.4.2) return. Otherwise ToPrimitive calls the method found. +/// An `@@toPrimitive` method on the object, in a realm with [`crate::Options::es2015`], is called +/// before either (ECMA-262 11th edition, section 7.1.1). fn unwrap_primitive(interp: &mut Interp, v: &Value, as_string: bool) -> JsResult> { let Value::Object(o) = v else { return Ok(None) }; let (primitive, proto, string) = match interp.heap.object(*o).map(|x| &x.class) { @@ -578,7 +580,11 @@ fn unwrap_primitive(interp: &mut Interp, v: &Value, as_string: bool) -> JsResult _ => return Ok(None), }; let (hint, name) = if string { (Hint::String, "toString") } else { (Hint::Number, "valueOf") }; - let p = if reaches_prototype(interp, *o, proto, name)? { primitive } else { interp.to_primitive(v, hint)? }; + let p = match interp.exotic_to_primitive(*o, v, hint)? { + Some(p) => p, + None if reaches_prototype(interp, *o, proto, name)? => primitive, + None => interp.ordinary_to_primitive(*o, v, hint)?, + }; Ok(Some(if string { Value::String(interp.to_str(&p)?) } else { Value::Number(interp.to_number(&p)?) })) } diff --git a/crates/js/src/chars.rs b/crates/js/src/chars.rs index 61b9a7f318..60df43513c 100644 --- a/crates/js/src/chars.rs +++ b/crates/js/src/chars.rs @@ -123,7 +123,7 @@ pub fn hex_value(c: u32) -> Option { } } -/// The value of the digit values `digits` in `radix` (8 or 16), rounded once to the nearest number +/// The value of the digit values `digits` in `radix` (2, 8 or 16), rounded once to the nearest number /// with ties to even (sections 7.8.3 and 9.3.1), or `None` when there are no digits. Digits are /// kept exactly in a `u128` while they fit; past that, each later digit counts only for its /// position and for whether any of the dropped bits is set. diff --git a/crates/js/src/host.rs b/crates/js/src/host.rs index 967d5e3656..a57abaea06 100644 --- a/crates/js/src/host.rs +++ b/crates/js/src/host.rs @@ -269,6 +269,14 @@ impl Interp { return Err(self.data_error(r, ErrorType::Type, &what)); } }; + // Each Symbol key the scan may visit takes a unit of fuel first. + let syms = self.object(id)?.syms.as_ref().map_or(0, |m| m.len()); + if syms > 0 { + crate::regexp_vm::use_fuel_n(self, syms as u64)?; + } + if self.object(id)?.syms.as_ref().is_some_and(|m| m.iter().any(|(_, p)| p.enumerable())) { + return Err(self.data_error(r, ErrorType::Type, "has a Symbol-keyed property, not plain data")); + } r.ancestors.push(id); let out = match shape { Shape::Array(length) => self.read_array(id, length, r), @@ -529,7 +537,14 @@ impl Interp { /// `v` as the string `String(v)` gives, within the limits of a crossing. fn read_text(&mut self, v: &Value, r: &mut Reading) -> JsResult { - let s = self.to_str(v)?; + let s = match v { + // `String(symbol)` gives `Symbol(description)` (ECMA-262 11th edition, section 21.1.1.1). + Value::Symbol(k) => match self.descriptive_string(k)? { + Value::String(s) => s, + _ => return Err(Abrupt::Internal("a Symbol's descriptive string is not a string".into())), + }, + _ => self.to_str(v)?, + }; self.charge_reading(r, s.len().saturating_mul(3).saturating_add(2))?; Ok(Data::String(s.to_rust_string())) } diff --git a/crates/js/src/host_tests.rs b/crates/js/src/host_tests.rs index 21cd2c0bc5..9fb7acc503 100644 --- a/crates/js/src/host_tests.rs +++ b/crates/js/src/host_tests.rs @@ -325,6 +325,45 @@ fn a_text_function_takes_each_argument_as_string_gives_it() { assert!(e.message.contains("no text"), "{}", e.message); } +#[test] +fn a_symbol_crosses_as_the_text_string_gives_it_and_never_as_data() { + let mut r = Realm::with_options(Options { es2015: true, ..Options::default() }, Limits { fuel: 10_000_000, ..Limits::default() }); + let seen = with_take(&mut r); + let texts: Rc>> = Rc::default(); + let log = texts.clone(); + let f: HostFunction = Rc::new(move |args| { + log.borrow_mut().extend(args); + Ok(Data::Undefined) + }); + r.define_host_object("text", vec![("of".into(), HostItem::TextFunction(f))]).unwrap(); + r.run("text.of(Symbol('tag'), Symbol())").unwrap(); + assert_eq!(texts.borrow().as_slice(), [Data::String("Symbol(tag)".into()), Data::String("Symbol()".into())]); + // An enumerable Symbol-keyed property is refused; one that is not enumerable is left out. + let probe = "var e = 'none'; var v = {a: 1}; v[Symbol('k')] = 2; try { host.take(v); } catch (x) { e = x.name + '|' + x.message; } e"; + let JsValue::String(out) = r.run(probe).unwrap() else { panic!("not a string") }; + assert!(out.starts_with("TypeError|") && out.contains("has a Symbol-keyed property"), "{out}"); + let probe = "var e = 'none'; var v = [1]; v[Symbol('k')] = 2; try { host.take({list: v}); } catch (x) { e = x.name + '|' + x.message; } e"; + let JsValue::String(out) = r.run(probe).unwrap() else { panic!("not a string") }; + assert!(out.starts_with("TypeError|") && out.contains(".list has a Symbol-keyed property"), "{out}"); + assert!(seen.borrow().is_empty(), "the function ran"); + r.run("var v = {a: 1}; Object.defineProperty(v, Symbol('k'), {value: 2}); host.take(v);").unwrap(); + assert_eq!(seen.borrow().as_slice(), [Data::Object(vec![("a".into(), Data::Number(1.0))])]); +} + +#[test] +fn checking_the_symbol_keys_of_a_value_takes_fuel() { + // Making the 20,000 hidden keys takes well under 3,000,000 units; the 500 crossings check + // 10,000,000 keys. + let mut r = Realm::with_options(Options { es2015: true, ..Options::default() }, Limits { fuel: 3_000_000, ..Limits::default() }); + with_take(&mut r); + let src = "var v = {}; for (var i = 0; i < 20000; i++) Object.defineProperty(v, Symbol(), {value: i}); \ + for (var j = 0; j < 500; j++) host.take(v);"; + match r.run(src) { + Err(RunError { kind: RunErrorKind::Limit(LimitKind::Fuel), .. }) => {} + other => panic!("{other:?}"), + } +} + #[test] fn errors_from_the_host_can_be_caught_and_an_abort_cannot() { let mut r = realm(1_000_000); diff --git a/crates/js/src/interp.rs b/crates/js/src/interp.rs index 13ac5cd834..742e31330f 100644 --- a/crates/js/src/interp.rs +++ b/crates/js/src/interp.rs @@ -2776,11 +2776,17 @@ impl Interp { if let Some(r) = self.exotic_to_primitive(*o, v, hint)? { return Ok(r); } + self.ordinary_to_primitive(*o, v, hint) + } + + /// [[DefaultValue]] (section 8.12.8) of the object `o`, which is `v`: ToPrimitive without the + /// `@@toPrimitive` method. + pub(crate) fn ordinary_to_primitive(&mut self, o: ObjId, v: &Value, hint: Hint) -> JsResult { // Without a hint, a Date object converts as with the String hint. - let date = hint == Hint::Default && matches!(self.heap.object(*o).map(|ob| &ob.class), Some(Class::Date(_))); + let date = hint == Hint::Default && matches!(self.heap.object(o).map(|ob| &ob.class), Some(Class::Date(_))); let order = if hint == Hint::String || date { ["toString", "valueOf"] } else { ["valueOf", "toString"] }; for name in order { - let f = self.get_from(*o, &key(name), v)?; + let f = self.get_from(o, &key(name), v)?; if self.is_callable(&f) { let r = self.call(&f, v, &[])?; if !matches!(r, Value::Object(_)) { @@ -2791,6 +2797,8 @@ impl Interp { Err(self.type_error("cannot convert the object to a primitive value")) } + /// ToNumber (section 9.3). In a realm with [`crate::Options::es2015`], a string may also be a + /// `0b` or `0o` literal (ECMA-262 11th edition, section 7.1.3.1). #[allow(clippy::wrong_self_convention)] pub(crate) fn to_number(&mut self, v: &Value) -> JsResult { Ok(match v { @@ -2798,7 +2806,7 @@ impl Interp { Value::Null => 0.0, Value::Bool(b) => f64::from(u8::from(*b)), Value::Number(n) => *n, - Value::String(s) => string_to_number(&flat_charged(self, s)?), + Value::String(s) => string_to_number(&flat_charged(self, s)?, self.options.es2015), Value::Symbol(_) => return Err(self.type_error("cannot convert a Symbol value to a number")), Value::Object(_) => { let p = self.to_primitive(v, Hint::Number)?; @@ -3035,7 +3043,7 @@ impl Interp { | (Value::Symbol(_), Value::Symbol(_)) | (Value::Object(_), Value::Object(_)) => return Ok(strict_eq(&x, &y)), (Value::Number(n), Value::String(s)) | (Value::String(s), Value::Number(n)) => { - return Ok(*n == string_to_number(&flat_charged(self, s)?)); + return Ok(*n == string_to_number(&flat_charged(self, s)?, self.options.es2015)); } (Value::Bool(v), _) => x = Value::Number(f64::from(u8::from(*v))), (_, Value::Bool(v)) => y = Value::Number(f64::from(u8::from(*v))), @@ -3105,9 +3113,10 @@ impl Interp { } } - /// A host value as a JavaScript value. A string is charged to the heap, and one that does not - /// fit in it ends the run with the heap limit. Everything the caller still needs must be - /// reachable from the roots. + /// A host value as a JavaScript value. A string or a Symbol's description is charged to the + /// heap before it is built, and one that does not fit in it ends the run with the heap limit. + /// A Symbol in a realm without [`crate::Options::es2015`] throws a `TypeError`. Everything the + /// caller still needs must be reachable from the roots. #[allow(clippy::wrong_self_convention)] pub(crate) fn from_js_value(&mut self, v: crate::JsValue) -> JsResult { Ok(match v { @@ -3122,12 +3131,15 @@ impl Interp { Value::str(&s) } crate::JsValue::Object(_) => Value::Object(self.new_object()), + crate::JsValue::Symbol(_) if !self.options.es2015 => { + return Err(self.type_error("a host function returned a Symbol in a realm without Symbol")); + } crate::JsValue::Symbol(description) => { - let units: Option> = description.map(|d| d.encode_utf16().collect()); - let bytes = crate::heap::SYMBOL_BYTES + units.as_ref().map_or(0, |u| string_bytes(u.len())); + let bytes = crate::heap::SYMBOL_BYTES + description.as_ref().map_or(0, |d| string_bytes(d.encode_utf16().count())); self.reserve_heap(bytes)?; self.heap.bytes += bytes; - Value::Symbol(crate::symbol::Sym::new(units.map(Str::from_units), false)) + let description = description.map(|d| Str::from_units(d.encode_utf16().collect())); + Value::Symbol(crate::symbol::Sym::new(description, false)) } }) } diff --git a/crates/js/src/lib.rs b/crates/js/src/lib.rs index c5e45af08f..4cdb639c85 100644 --- a/crates/js/src/lib.rs +++ b/crates/js/src/lib.rs @@ -55,8 +55,9 @@ //! and iterator objects with a `next` method from `Array.prototype.values`, `keys`, `entries` and //! `@@iterator`, `String.prototype[@@iterator]` (by code point) and every `arguments` object. A //! Symbol converted to a string or a number without `String(symbol)` or `toString` throws a -//! `TypeError`. Every iterator step takes fuel, and every Symbol and registry entry counts against -//! the heap limit. +//! `TypeError`. A string converts to a number in the `0b` and `0o` forms as well. Every iterator +//! step and every prototype a Symbol-keyed lookup passes takes fuel, and every Symbol and registry +//! entry counts against the heap limit. #![forbid(unsafe_code)] pub mod ast; @@ -113,8 +114,9 @@ pub struct Options { /// Read and run E4X (ECMA-357). Off, XML syntax is an error and a realm has no XML built-ins. pub e4x: bool, /// Give a realm the later editions' built-ins this engine has: `Symbol` with Symbol-keyed - /// properties and the iterators of arrays, strings and `arguments` objects. Off, a realm has - /// the ES5.1 built-ins only, as the app's scripts expect. + /// properties and the iterators of arrays, strings and `arguments` objects, with `0b` and `0o` + /// strings converting to numbers. Off, a realm has the ES5.1 built-ins only, as the app's + /// scripts expect. pub es2015: bool, } diff --git a/crates/js/src/realm.rs b/crates/js/src/realm.rs index 08d9913948..ae3021dada 100644 --- a/crates/js/src/realm.rs +++ b/crates/js/src/realm.rs @@ -110,7 +110,8 @@ impl Interrupt { } /// A value passed between a script and the host. An object is given by its class name, and a -/// Symbol by its description; a Symbol the host passes in is a new Symbol each time. +/// Symbol by its description; a Symbol the host passes in is a new Symbol each time, and one a +/// host function returns in a realm without [`Options::es2015`] throws a `TypeError`. #[derive(Clone, Debug, PartialEq)] pub enum JsValue { Undefined, diff --git a/crates/js/src/symbol.rs b/crates/js/src/symbol.rs index 2c25ebd099..34fd489fa3 100644 --- a/crates/js/src/symbol.rs +++ b/crates/js/src/symbol.rs @@ -127,6 +127,7 @@ impl SymProps { let (_, prop) = self.entries.get_mut(i)?.take()?; if self.entries.len() > 16 && self.index.len() * 2 < self.entries.len() { self.entries.retain(Option::is_some); + self.entries.shrink_to_fit(); self.index = self.entries.iter().enumerate().filter_map(|(i, e)| e.as_ref().map(|(k, _)| (k.clone(), i))).collect(); } Some(prop) @@ -304,8 +305,9 @@ impl Interp { Ok(self.object(id)?.syms.as_ref().and_then(|m| m.get(k)).cloned()) } - /// The property `k` found on the object or its prototype chain. - pub(crate) fn find_sym(&self, id: ObjId, k: &Sym) -> JsResult> { + /// The property `k` found on the object or its prototype chain. Each step to a prototype takes + /// a unit of fuel. + pub(crate) fn find_sym(&mut self, id: ObjId, k: &Sym) -> JsResult> { let mut cur = Some(id); let mut steps = 0usize; while let Some(o) = cur { @@ -313,6 +315,9 @@ impl Interp { return Ok(Some(p)); } cur = self.object(o)?.proto; + if cur.is_some() { + self.use_fuel()?; + } steps += 1; if steps > 1_000_000 { return Err(crate::interp::Abrupt::Internal("prototype chain too long".into())); @@ -464,7 +469,7 @@ impl Interp { } } - pub(crate) fn has_pk(&self, id: ObjId, k: &PropKey) -> JsResult { + pub(crate) fn has_pk(&mut self, id: ObjId, k: &PropKey) -> JsResult { match k { PropKey::Str(name) => self.has_property(id, name), PropKey::Sym(s) => Ok(self.find_sym(id, s)?.is_some()), @@ -579,3 +584,24 @@ impl Interp { } } } + +#[cfg(test)] +mod tests { + use super::{Sym, SymProps}; + use crate::heap::{OPEN, Prop}; + use crate::value::Value; + + #[test] + fn removing_most_symbol_keys_gives_back_their_room_and_keeps_the_order() { + let mut m = SymProps::default(); + let keys: Vec = (0..100).map(|_| Sym::new(None, false)).collect(); + for k in &keys { + m.insert(k.clone(), Prop::Data { value: Value::Undefined, flags: OPEN }); + } + for k in &keys[..90] { + m.remove(k); + } + assert!(m.entries.capacity() < 64, "{}", m.entries.capacity()); + assert_eq!(m.iter().map(|(k, _)| k.clone()).collect::>(), keys[90..]); + } +} diff --git a/crates/js/src/symbol_tests.rs b/crates/js/src/symbol_tests.rs index d877e04106..5e372bdafd 100644 --- a/crates/js/src/symbol_tests.rs +++ b/crates/js/src/symbol_tests.rs @@ -219,6 +219,70 @@ fn an_array_iterator_keeps_its_object_while_reading_its_length_runs_script() { assert_eq!(string(src), "x false true"); } +#[test] +fn binary_and_octal_strings_are_numbers_in_an_es2015_realm_only() { + for length in ["0b10", "0o2", "2"] { + let src = format!( + "var it = Array.prototype.values.call({{0: 'first', 1: 'second', length: '{length}'}}); \ + var a = it.next(), b = it.next(); a.value + ' ' + b.value + ' ' + it.next().done" + ); + assert_eq!(string(&src), "first second true", "{length}"); + } + truth("Number('0b101') === 5 && +'0O17' === 15 && '0b11' == 3 && isNaN('0b2') && isNaN('-0o1')"); + let src = "isNaN(Number('0b10')) && isNaN(+'0o2') && '0b1' != 1"; + assert_eq!(Realm::with_options(Options::default(), Limits::default()).run(src), Ok(JsValue::Bool(true))); +} + +#[test] +fn json_calls_the_to_primitive_method_of_a_wrapper() { + let hook = "w[Symbol.toPrimitive] = function (hint) { return hint === 'number' ? 2 : 'b'; };"; + truth(&format!("var w = new String('x'); {hook} JSON.stringify(w) === '\"b\"'")); + truth(&format!("var w = new String('x'); delete String.prototype.toString; {hook} JSON.stringify(w) === '\"b\"'")); + truth(&format!("var w = new String('x'); {hook} JSON.stringify({{a: 1, b: 2}}, [w]) === '{{\"b\":2}}'")); + truth(&format!("var w = new Number(5); {hook} JSON.stringify([w], null, w) === '[\\n 2\\n]'")); + truth("JSON.stringify([new String('x'), new Number(1)], null, new Number(1)) === '[\\n \"x\",\\n 1\\n]'"); +} + +#[test] +fn a_host_function_returns_a_symbol_only_in_an_es2015_realm() { + let symbol = |_: &[JsValue]| -> Result { Ok(JsValue::Symbol(Some("from host".into()))) }; + let mut realm = es2015(Limits::default()); + realm.define_function("make", symbol); + assert_eq!(realm.run("var s = make(); typeof s === 'symbol' && String(s) === 'Symbol(from host)' && s !== make()"), Ok(JsValue::Bool(true))); + let mut realm = Realm::with_options(Options::default(), Limits::default()); + realm.define_function("make", symbol); + let src = "try { make(); 'none'; } catch (e) { (e instanceof TypeError) + ' ' + typeof Symbol; }"; + assert_eq!(realm.run(src), Ok(JsValue::String("true undefined".into()))); +} + +#[test] +fn a_host_symbol_description_counts_against_the_heap_before_it_is_made() { + let mut realm = es2015(Limits { heap_bytes: 1 << 20, ..Limits::default() }); + realm.define_function("make", |_| Ok(JsValue::Symbol(Some("d".repeat(1 << 20))))); + match realm.run("make()") { + Err(RunError { kind: RunErrorKind::Limit(LimitKind::Heap), .. }) => {} + other => panic!("{other:?}"), + } + let mut realm = es2015(Limits { heap_bytes: 1 << 20, ..Limits::default() }); + realm.define_function("make", |_| Ok(JsValue::Symbol(Some("d".repeat(1_000))))); + assert_eq!(realm.run("make().description.length"), Ok(JsValue::Number(1_000.0))); +} + +#[test] +fn a_symbol_lookup_takes_fuel_for_each_prototype() { + // Building the chain takes about 20,000 units; each lookup of an absent Symbol walks all 2,000 + // prototypes, so the 100 lookups take 200,000 more. + let src = "var s = Symbol(), o = {}; for (var i = 0; i < 2000; i++) o = Object.create(o); \ + for (var j = 0; j < 100; j++) s in o;"; + match es2015(Limits { fuel: 150_000, ..Limits::default() }).run(src) { + Err(RunError { kind: RunErrorKind::Limit(LimitKind::Fuel), .. }) => {} + other => panic!("{other:?}"), + } + let src = "var s = Symbol(), root = {}, o = root; root[s] = 'found'; for (var i = 0; i < 50; i++) o = Object.create(o); \ + o[s] === 'found' && s in o && !o.hasOwnProperty(s)"; + truth(src); +} + #[test] fn iterator_steps_take_fuel() { let mut realm = es2015(Limits { fuel: 5_000, ..Limits::default() }); diff --git a/crates/js/src/value.rs b/crates/js/src/value.rs index 66005773e2..4911c6e36b 100644 --- a/crates/js/src/value.rs +++ b/crates/js/src/value.rs @@ -263,9 +263,10 @@ pub(crate) fn is_str_space(u: u16) -> bool { crate::chars::is_whitespace(u32::from(u)) || crate::chars::is_line_terminator(u32::from(u)) } -/// ToNumber applied to a string (section 9.3.1): the StringNumericLiteral grammar, NaN for -/// anything else. -pub(crate) fn string_to_number(units: &[u16]) -> f64 { +/// ToNumber applied to a string (section 9.3.1): the StringNumericLiteral grammar, with the `0b` +/// and `0o` literals of ECMA-262 11th edition, section 7.1.3.1, as well when `binary_octal` is +/// set; NaN for anything else. +pub(crate) fn string_to_number(units: &[u16], binary_octal: bool) -> f64 { let start = units.iter().position(|&u| !is_str_space(u)).unwrap_or(units.len()); let end = units.iter().rposition(|&u| !is_str_space(u)).map_or(start, |i| i + 1); let Some(text) = units.get(start..end) else { return f64::NAN }; @@ -279,6 +280,15 @@ pub(crate) fn string_to_number(units: &[u16]) -> f64 { } return crate::chars::radix_value(hex.bytes().filter_map(|b| crate::chars::hex_value(u32::from(b))), 16).unwrap_or(f64::NAN); } + if binary_octal { + for (prefix, radix) in [("0b", 2), ("0B", 2), ("0o", 8), ("0O", 8)] { + let Some(digits) = s.strip_prefix(prefix) else { continue }; + if digits.is_empty() || !digits.chars().all(|c| c.is_digit(radix)) { + return f64::NAN; + } + return crate::chars::radix_value(digits.chars().filter_map(|c| c.to_digit(radix)), radix).unwrap_or(f64::NAN); + } + } let (sign, body) = match s.as_bytes().first() { Some(b'+') => (1.0, &s[1..]), Some(b'-') => (-1.0, &s[1..]), @@ -386,19 +396,32 @@ mod tests { ("-Infinity", f64::NEG_INFINITY), ]; for (s, want) in cases { - assert_eq!(string_to_number(&u(s)), *want, "{s:?}"); + assert_eq!(string_to_number(&u(s), false), *want, "{s:?}"); } for s in ["inf", "nan", "1_0", "0x", "1e", ".", "--1", "0x-1", "infinity", "1 2"] { - assert!(string_to_number(&u(s)).is_nan(), "{s:?}"); + assert!(string_to_number(&u(s), false).is_nan(), "{s:?}"); + } + } + + #[test] + fn binary_and_octal_strings_convert_only_when_asked() { + for (s, want) in [("0b10", 2.0), ("0B11", 3.0), (" 0o17 ", 15.0), ("0O7", 7.0), ("0x10", 16.0), ("2", 2.0)] { + assert_eq!(string_to_number(&u(s), true), want, "{s:?}"); + } + for s in ["0b", "0b2", "0o8", "-0b1", "+0o1", "0b1.0", "0o"] { + assert!(string_to_number(&u(s), true).is_nan(), "{s:?}"); + } + for s in ["0b10", "0o2"] { + assert!(string_to_number(&u(s), false).is_nan(), "{s:?}"); } } #[test] fn hex_strings_round_once_to_the_nearest_number() { - assert_eq!(string_to_number(&u("0xc83ce80553ee648")), 0xc83_ce80_553e_e648_u64 as f64); + assert_eq!(string_to_number(&u("0xc83ce80553ee648"), false), 0xc83_ce80_553e_e648_u64 as f64); // 2^136 + 2^83 + 1: a set bit past 128 bits rounds the half-way case up. let digits = format!("0x1{}8{}1", "0".repeat(13), "0".repeat(19)); - assert_eq!(string_to_number(&u(&digits)), 2f64.powi(136) + 2f64.powi(84)); + assert_eq!(string_to_number(&u(&digits), false), 2f64.powi(136) + 2f64.powi(84)); } #[test] diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 3264973bf5..2579945202 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1082,7 +1082,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - `vectorcraft-js` provides the ECMAScript 5.1 built-ins `Object` with its property-descriptor functions, `create`, `keys`, `seal` and `freeze` (section 15.2), `Function.prototype.bind` (15.3.4.5), `Array` with every ES5 method (15.4), the error types (15.11), `Math` (15.8), `JSON` with revivers, replacers and indentation (15.12), and the global functions with Annex B's `escape` and `unescape` (15.1, B.2). The array methods work on array-like objects. A method visits only the indices that exist when its range is longer than 4,096 indices and more than 8 times the properties on the object and its prototypes, so `new Array(4294967295).join("")` ends at once; a shorter range is visited index by index, holes included, and each index takes fuel. `join` writes a cycle back to an array as an empty string, `JSON.stringify` throws a `TypeError` on a cycle, and deep `JSON` nesting uses no native stack. Every loop takes fuel and every result is checked against the heap limit. `cargo xtask test262` runs the suite's ES5 built-in tests that need only these built-ins: 6,798 of 6,866 runs pass (the 34 failing tests expect rules of later editions). It also fetches the `json2.js` polyfill at a pinned commit and checks that its `stringify` and `parse` agree with the built-in `JSON`. Tests: `crates/js/src/builtins_tests.rs`, `crates/js/tests/test262.rs`, `crates/js/tests/json2.rs`. - `vectorcraft-js` has `String`, `Number`, `RegExp` and `Date` as ECMAScript 5.1 defines them (sections 15.5, 15.7, 15.9 and 15.10, https://262.ecma-international.org/5.1/), with Annex B's `substr`, `getYear`, `setYear` and `toGMTString`. `toFixed`, `toExponential` and `toPrecision` format a number from its exact decimal value, and `toString(radix)` writes any base from 2 to 36. Regular expressions (flags `g`, `i` and `m`) run on a backtracking matcher whose choice points and capture state count against the heap limit and which takes fuel for every step, so a catastrophic pattern stops at the fuel limit and 50,000 nested groups give a `SyntaxError` at the default depth limit. A string method that would build a string past the heap limit stops before it allocates. `Date` reads the clock and time zone the host sets (`Realm::set_clock`, `Realm::set_time_zone`; local time is UTC by default). `cargo xtask test262` runs the suite's `built-ins` tests for the four (https://github.com/tc39/test262): of the runs of the ES5 tests that need only the built-ins present, 1,379 of 1,411 pass for `String`, 298 of 298 for `Number`, 954 of 988 for `RegExp` and 8 of 8 for `Date`. The others expect later editions' rules (built-in functions whose `length` can be deleted, flags given with a RegExp object, a negative `lastIndex`, `RegExp.prototype` as a plain object, and `RegExp.prototype`'s `global`, `ignoreCase` and `multiline` properties that can be deleted). Tests: `crates/js/src/text_tests.rs`, `crates/js/tests/test262.rs`. - `cargo xtask test262` also reads the suite's Annex B tests (https://tc39.es/ecma262/#sec-additional-ecmascript-features-for-web-browsers), whichever edition they name. It parses the 819 tests under `test/annexB/language` without a feature tag in the modes their flags give, so a `for`-`in` variable with an initializer must parse in sloppy code and give a `SyntaxError` in strict code (682 of 843 runs pass), and it runs those tests and the `test/annexB/built-ins` tests for `String`, `Date`, `RegExp` and `Function` that need only the built-ins present (263 of 667 runs pass for the language tests and 56 of 252 for the built-ins). Failures go to `annexb-parse-failures.txt`, `annexb-language-failures.txt` and `annexb-builtins-failures.txt` beside the suite. A conformance failure does not fail the tests, but an interpreter panic fails `annex_b_runs`, so `cargo xtask test262` exits non-zero. A folder or file the runner cannot read also fails the test that reads it. The runner reads only regular files inside the suite, up to 8 MiB each, and does not follow symbolic links. Tests: `crates/js/tests/test262.rs`. - - With `Options::es2015` set, which it is not by default, a `vectorcraft-js` realm also has `Symbol` (ECMA-262 11th edition, section 19.4, https://262.ecma-international.org/11.0/): `Symbol(description)`, which `new` refuses with a `TypeError`, the `description` getter, `toString`, `valueOf`, and `Symbol.for` and `Symbol.keyFor` over a registry that lasts as long as the realm. `typeof` gives `"symbol"`. Symbols are property keys: `Object.getOwnPropertySymbols` lists an object's Symbol keys in the order they were added, `Object.defineProperty`, `getOwnPropertyDescriptor`, `freeze`, `seal`, `in`, `delete` and `hasOwnProperty` take them, and `for`-`in`, `Object.keys`, `Object.getOwnPropertyNames` and `JSON.stringify` leave them out. `String(symbol)` and `symbol.toString()` give `Symbol(description)`; any other conversion of a Symbol to a string or a number, such as `Symbol() + ''`, throws a `TypeError`. The well-known Symbols `Symbol.iterator`, `Symbol.asyncIterator`, `Symbol.hasInstance`, `Symbol.toPrimitive` and `Symbol.toStringTag` are defined: conversion to a primitive calls an object's `@@toPrimitive` method, `instanceof` calls the right side's `@@hasInstance` method, and `Object.prototype.toString` writes a string `@@toStringTag`. Nothing reads `Symbol.asyncIterator` yet. `Array.prototype.values` (also `Array.prototype[Symbol.iterator]`), `keys` and `entries`, `String.prototype[Symbol.iterator]` and every `arguments` object's `Symbol.iterator` return iterators whose `next()` gives `{value, done}` objects; a string iterator steps by code point and keeps a surrogate pair together. An array iterator reads the `length` at each step, so it visits elements added during the walk. Each step takes fuel, and each Symbol and registry entry counts against the heap limit. A realm without the option, including the one the app runs scripts in, has none of these names. The language does not have `for`-`of`, spread or destructuring yet, so scripts call `next()` themselves. `cargo xtask test262` runs the suite's tests of `Symbol`, `ArrayIteratorPrototype`, `StringIteratorPrototype`, `Object.getOwnPropertySymbols`, `Array.prototype.values`, `keys`, `entries` and `Symbol.iterator`, and `String.prototype[Symbol.iterator]` that need only these built-ins and parse as ES5, in such a realm: 164 of 216 runs pass (6 passed before), and the 52 others expect a configurable function `length` and a function `name` property. Tests: `crates/js/src/symbol_tests.rs`, `crates/js/tests/test262.rs`. + - With `Options::es2015` set, which it is not by default, a `vectorcraft-js` realm also has `Symbol` (ECMA-262 11th edition, section 19.4, https://262.ecma-international.org/11.0/): `Symbol(description)`, which `new` refuses with a `TypeError`, the `description` getter, `toString`, `valueOf`, and `Symbol.for` and `Symbol.keyFor` over a registry that lasts as long as the realm. `typeof` gives `"symbol"`. Symbols are property keys: `Object.getOwnPropertySymbols` lists an object's Symbol keys in the order they were added, `Object.defineProperty`, `getOwnPropertyDescriptor`, `freeze`, `seal`, `in`, `delete` and `hasOwnProperty` take them, and `for`-`in`, `Object.keys`, `Object.getOwnPropertyNames` and `JSON.stringify` leave them out. `String(symbol)` and `symbol.toString()` give `Symbol(description)`; any other conversion of a Symbol to a string or a number, such as `Symbol() + ''`, throws a `TypeError`. A string such as `'0b10'` or `'0o2'` converts to a number, as section 7.1.3.1 gives. The well-known Symbols `Symbol.iterator`, `Symbol.asyncIterator`, `Symbol.hasInstance`, `Symbol.toPrimitive` and `Symbol.toStringTag` are defined: conversion to a primitive calls an object's `@@toPrimitive` method, `instanceof` calls the right side's `@@hasInstance` method, and `Object.prototype.toString` writes a string `@@toStringTag`; `JSON.stringify` calls a String or Number object's `@@toPrimitive` method too. Nothing reads `Symbol.asyncIterator` yet. `Array.prototype.values` (also `Array.prototype[Symbol.iterator]`), `keys` and `entries`, `String.prototype[Symbol.iterator]` and every `arguments` object's `Symbol.iterator` return iterators whose `next()` gives `{value, done}` objects; a string iterator steps by code point and keeps a surrogate pair together. An array iterator reads the `length` at each step, so it visits elements added during the walk. Each step takes fuel, as does each prototype a Symbol-keyed lookup passes, and each Symbol and registry entry counts against the heap limit. A realm without the option, including the one the app runs scripts in, has none of these names, and a host function that returns a Symbol there throws a `TypeError`. The language does not have `for`-`of`, spread or destructuring yet, so scripts call `next()` themselves. `cargo xtask test262` runs the suite's tests of `Symbol`, `ArrayIteratorPrototype`, `StringIteratorPrototype`, `Object.getOwnPropertySymbols`, `Array.prototype.values`, `keys`, `entries` and `Symbol.iterator`, and `String.prototype[Symbol.iterator]` that need only these built-ins and parse as ES5, in such a realm: 164 of 216 runs pass (6 passed before), and the 52 others expect a configurable function `length` and a function `name` property. Tests: `crates/js/src/symbol_tests.rs`, `crates/js/tests/test262.rs`. - Scripts: `cargo xtask corpus --scripts` fetches 397 public scripts and 1 file they include from 19 MIT and Apache-2.0 repositories at pinned commits into `corpus/scripts` (gitignored), each repository's license file beside its scripts. `xtask/script-corpus.txt` lists every file with its size and SHA-256, and a download is checked against both before it replaces anything; one more candidate is left out because it is over the 1 MiB limit for one script. `cargo xtask scripts --pass-rate [--report ]` runs each script headless in a process of its own (a new document, 5,000,000 instructions, no dialog answers, file reads only in its repository's folder and a new folder of its own, file writes only in that folder, no command it can start, stopped after 10 seconds) and writes a JSON report: the pass rate overall, per repository and for the scripts without dialogs or windows, how many parse, and each script's outcome. Script failures never fail the command, and without the corpus it skips. These limits are VectorCraft's own. Tests: `xtask/src/script_corpus.rs`, `crates/engine/tests/script_corpus.rs`. - With `Options::e4x` set, an E4X name standing alone (`@a`, `@ns::a`, `@[expr]`, `ns::a`, `*`) inside `with` or a filter predicate can be assigned, with `=` or a compound operator, incremented, decremented, deleted and used as a `for` or `for each` variable, as well as read. Each of these uses the nearest XML or XMLList value in scope that holds the name and evaluates the name once. When no XML value in scope holds the name, the read or write throws a `ReferenceError` before the right-hand side runs and creates no child or attribute, as ECMA-357 section 11.1 (https://ecma-international.org/publications-and-standards/standards/ecma-357/) specifies, so a filter such as `list.(@id == '1')` throws when an item has no `@id` and no outer XML value holds one. Tests: `crates/js/src/xml_tests.rs`. - `vectorcraft-js` runs ECMAScript for XML (ECMA-357, 2nd edition, https://ecma-international.org/publications-and-standards/standards/ecma-357/) when `Options::e4x` is set, which it is not by default: XML and XMLList literals with embedded `{}` expressions, the `..`, `.@`, `.*`, `.()` and `::` selectors, assignment and `delete` on selected nodes, `for each`, `default xml namespace`, and the `XML`, `XMLList`, `Namespace` and `QName` objects with their methods and settings. `xml.xpath(expression[, variables])` evaluates an XPath 1.0 expression (https://www.w3.org/TR/1999/REC-xpath-19991116/) with all 13 axes and the 27 core functions, and returns the selected nodes as an XMLList in document order without repeats. Each property of `variables` binds the variable of its name, an XMLList runs the expression on each of its elements in turn, and a prefix in a name test resolves through the context element's in-scope namespaces. An expression that breaks the grammar gives a `SyntaxError`; an unknown function, a wrong argument count, an unbound prefix or variable, and a result that is not a node-set or that holds the root or a namespace node give a `TypeError`. `id()` selects nothing, and evaluation uses no native stack, takes fuel and counts against the heap limit. `` in an XML string gives a `SyntaxError`. An XML declaration at the start of an XML string, after optional white space, is checked against XML 1.0's grammar (https://www.w3.org/TR/xml/#NT-XMLDecl): a version of `1.` and digits, then an optional encoding name and an optional standalone `yes` or `no`, in that order; any other declaration, or one with a character XML does not allow, gives a `SyntaxError`. The parser takes fuel for the length of every name, white space run and declaration it scans, and for the text it searched when a quote, CDATA section, comment or processing instruction is not closed. Parsing, serializing, comparing and copying trees use no native stack, and each takes fuel and counts against the heap limit. Inserting a node into itself or its descendants throws a `TypeError` before the tree changes, a literal or XML string nested past `Options::max_depth` gives a `SyntaxError`, and a tree built past that depth stops at the heap limit. Tests: `crates/js/src/xml_tests.rs`. From e4751813293ca576c08eb8900e88910e6e7c98d7 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 22 Nov 2026 01:56:22 -0800 Subject: [PATCH 051/151] JavaScript: Date.prototype[@@toPrimitive] and ToPrimitive fixes in ES2015 realms In a realm with `Options::es2015`, `Date.prototype[Symbol.toPrimitive]` converts with `toString` first for the hints "string" and "default" and with `valueOf` first for "number" (ECMA-262 11th edition, section 20.4.4.45). An object without an `@@toPrimitive` method, a Date whose own method is `null` or `undefined` included, converts without a hint with `valueOf` first (section 7.1.1.1), so `d + 1` gives 8 when `valueOf` returns 7. A realm without the option keeps the ES5 order for a Date. `JSON.stringify` converts a Number or String object with ToPrimitive. A `valueOf` or `toString` deleted from the object's own prototype is now looked up further along the chain, so `Object.prototype.toString` is called instead of the stored primitive value being returned. A Symbol that an object's `@@toPrimitive` method gives as a property key is rooted while the property is read or incremented, so it and its description still count against the heap when a getter starts a collection. --- crates/js/src/builtins/json.rs | 42 ++++----------------- crates/js/src/builtins/symbol.rs | 32 +++++++++++++--- crates/js/src/builtins_tests.rs | 4 ++ crates/js/src/interp.rs | 7 +++- crates/js/src/lib.rs | 6 ++- crates/js/src/symbol.rs | 8 ++-- crates/js/src/symbol_tests.rs | 65 ++++++++++++++++++++++++++++++++ docs/target-app-parity.md | 2 +- 8 files changed, 118 insertions(+), 48 deletions(-) diff --git a/crates/js/src/builtins/json.rs b/crates/js/src/builtins/json.rs index 6fc8544e9d..e01a47b085 100644 --- a/crates/js/src/builtins/json.rs +++ b/crates/js/src/builtins/json.rs @@ -565,47 +565,21 @@ fn resolve_rooted(interp: &mut Interp, settings: &Settings, holder: ObjId, k: &K /// ToNumber of a Number object, or ToString of a String object (of either when `as_string` is /// set), as section 15.12.3 applies them in Str step 4, step 4.b.ii and step 5. Returns `None` -/// for any other value. When the method that [[DefaultValue]] (section 8.12.8) calls first is not -/// found on the object or on its prototype chain before the object's standard prototype, the -/// result is the object's [[PrimitiveValue]] (sections 8.6.2 and 9.9), the value that -/// `Number.prototype.valueOf` (15.7.4.4), `Number.prototype.toString` (15.7.4.2) and -/// `String.prototype.toString` (15.5.4.2) return. Otherwise ToPrimitive calls the method found. -/// An `@@toPrimitive` method on the object, in a realm with [`crate::Options::es2015`], is called -/// before either (ECMA-262 11th edition, section 7.1.1). +/// for any other value. The conversion is ToPrimitive (section 9.1) with the Number or String +/// hint, so `valueOf` and `toString` are looked up along the object's whole prototype chain, and +/// in a realm with [`crate::Options::es2015`] an `@@toPrimitive` method on the object is called +/// first (ECMA-262 11th edition, section 7.1.1). fn unwrap_primitive(interp: &mut Interp, v: &Value, as_string: bool) -> JsResult> { let Value::Object(o) = v else { return Ok(None) }; - let (primitive, proto, string) = match interp.heap.object(*o).map(|x| &x.class) { - Some(Class::Number(n)) => (Value::Number(*n), interp.intrinsics.number_proto, as_string), - Some(Class::String(s)) => (Value::String(s.clone()), interp.intrinsics.string_proto, true), + let string = match interp.heap.object(*o).map(|x| &x.class) { + Some(Class::Number(_)) => as_string, + Some(Class::String(_)) => true, _ => return Ok(None), }; - let (hint, name) = if string { (Hint::String, "toString") } else { (Hint::Number, "valueOf") }; - let p = match interp.exotic_to_primitive(*o, v, hint)? { - Some(p) => p, - None if reaches_prototype(interp, *o, proto, name)? => primitive, - None => interp.ordinary_to_primitive(*o, v, hint)?, - }; + let p = interp.to_primitive(v, if string { Hint::String } else { Hint::Number })?; Ok(Some(if string { Value::String(interp.to_str(&p)?) } else { Value::Number(interp.to_number(&p)?) })) } -/// Whether looking up `name` from `o` reaches the object `proto` on the prototype chain before -/// any object on the way, `proto` included, has its own property `name`. -fn reaches_prototype(interp: &mut Interp, o: ObjId, proto: ObjId, name: &str) -> JsResult { - let k = key(name); - let mut cur = Some(o); - while let Some(id) = cur { - interp.use_fuel()?; - if interp.get_own_property(id, &k)?.is_some() { - return Ok(false); - } - if id == proto { - return Ok(true); - } - cur = interp.heap.object(id).and_then(|x| x.proto); - } - Ok(false) -} - /// Quote (section 15.12.3): the string in double quotes with the characters JSON escapes. fn write_quoted(interp: &mut Interp, out: &mut Builder, s: &[u16]) -> JsResult<()> { out.push_units(interp, &[QUOTE])?; diff --git a/crates/js/src/builtins/symbol.rs b/crates/js/src/builtins/symbol.rs index f0afe7b2f8..b671f51e42 100644 --- a/crates/js/src/builtins/symbol.rs +++ b/crates/js/src/builtins/symbol.rs @@ -1,12 +1,12 @@ //! `Symbol` (ECMA-262 11th edition, section 19.4, ): //! the constructor with `Symbol.for`, `Symbol.keyFor` and the well-known Symbols, the methods of -//! `Symbol.prototype`, `Object.getOwnPropertySymbols` (section 19.1.2.10) and -//! `Function.prototype[@@hasInstance]` (section 19.2.3.6). Installed in a realm with -//! [`crate::Options::es2015`] only. +//! `Symbol.prototype`, `Object.getOwnPropertySymbols` (section 19.1.2.10), +//! `Function.prototype[@@hasInstance]` (section 19.2.3.6) and `Date.prototype[@@toPrimitive]` +//! (section 20.4.4.45). Installed in a realm with [`crate::Options::es2015`] only. use super::{arg, constructor, create_at, data, method, native, new_array}; use crate::heap::{CONFIGURABLE, Class, NativeFn, NativeKind, ObjId, Object, Prop, SYMBOL_BYTES, string_bytes}; -use crate::interp::{Interp, JsResult}; +use crate::interp::{Hint, Interp, JsResult}; use crate::symbol::{Es2015Objects, REGISTRY_ENTRY_BYTES, Sym, WellKnown}; use crate::value::{Str, Value}; @@ -37,7 +37,9 @@ pub(super) fn install(interp: &mut Interp, object_ctor: ObjId) -> JsResult<()> { let getter = native(interp, "get description", description, 0, NativeKind::Plain, false)?; interp.define(proto, crate::heap::key("description"), Prop::Accessor { get: Some(getter), set: None, flags: CONFIGURABLE })?; interp.define_sym(proto, to_string_tag, Prop::Data { value: Value::str("Symbol"), flags: CONFIGURABLE })?; - sym_method(interp, proto, to_primitive, "[Symbol.toPrimitive]", symbol_to_primitive, 1, CONFIGURABLE)?; + sym_method(interp, proto, to_primitive.clone(), "[Symbol.toPrimitive]", symbol_to_primitive, 1, CONFIGURABLE)?; + let date_proto = interp.intrinsics.date_proto; + sym_method(interp, date_proto, to_primitive, "[Symbol.toPrimitive]", date_to_primitive, 1, CONFIGURABLE)?; method(interp, object_ctor, "getOwnPropertySymbols", get_own_property_symbols, 1)?; let function_proto = interp.intrinsics.function_proto; @@ -138,6 +140,26 @@ fn symbol_to_primitive(interp: &mut Interp, this: Value, _: &[Value], _: bool) - this_symbol(interp, &this, "[Symbol.toPrimitive]").map(Value::Symbol) } +/// `Date.prototype[@@toPrimitive](hint)` (section 20.4.4.45): OrdinaryToPrimitive of any object, +/// `toString` first for the hints `"string"` and `"default"` and `valueOf` first for `"number"`. +/// Any other hint, or a `this` that is not an object, throws a `TypeError`. +fn date_to_primitive(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { + let Value::Object(o) = this else { + return Err(interp.type_error("Date.prototype[Symbol.toPrimitive] was called on a value that is not an object")); + }; + // The longest hint has 7 units, so a longer string is refused before it is flattened. + let name = match arg(args, 0) { + Value::String(s) if s.len() <= 7 => String::from_utf16_lossy(&s.flat()), + _ => String::new(), + }; + let hint = match name.as_str() { + "string" | "default" => Hint::String, + "number" => Hint::Number, + _ => return Err(interp.type_error("Date.prototype[Symbol.toPrimitive] was given a hint that is not \"string\", \"number\" or \"default\"")), + }; + interp.ordinary_to_primitive(o, &this, hint) +} + /// `Object.getOwnPropertySymbols(o)` (section 19.1.2.10): the object's own Symbol keys in the /// order they were added. fn get_own_property_symbols(interp: &mut Interp, _: Value, args: &[Value], _: bool) -> JsResult { diff --git a/crates/js/src/builtins_tests.rs b/crates/js/src/builtins_tests.rs index 0a70e80433..c009dddc9a 100644 --- a/crates/js/src/builtins_tests.rs +++ b/crates/js/src/builtins_tests.rs @@ -684,6 +684,10 @@ fn json_stringify_unwraps_number_string_and_boolean_objects() { assert_eq!(string("Object.prototype.valueOf = function () { return 9; }; JSON.stringify(Object(3))"), "3"); assert_eq!(string("Object.getPrototypeOf(Object(1)).valueOf = function () { return 4; }; JSON.stringify(Object(3))"), "4"); assert_eq!(string("Object.getPrototypeOf(Object('')).toString = function () { return 'q'; }; JSON.stringify(Object('abc'))"), "\"q\""); + // Once the own prototype's method is deleted, the lookup goes on to Object.prototype. + let over = "Object.prototype.toString = function () { return '7'; };"; + assert_eq!(string(&format!("{over} delete String.prototype.toString; JSON.stringify(Object('abc'))")), "\"7\""); + assert_eq!(string(&format!("{over} delete Number.prototype.valueOf; delete Number.prototype.toString; JSON.stringify(Object(3))")), "7"); } #[test] diff --git a/crates/js/src/interp.rs b/crates/js/src/interp.rs index 742e31330f..3c6f73cb64 100644 --- a/crates/js/src/interp.rs +++ b/crates/js/src/interp.rs @@ -2782,8 +2782,11 @@ impl Interp { /// [[DefaultValue]] (section 8.12.8) of the object `o`, which is `v`: ToPrimitive without the /// `@@toPrimitive` method. pub(crate) fn ordinary_to_primitive(&mut self, o: ObjId, v: &Value, hint: Hint) -> JsResult { - // Without a hint, a Date object converts as with the String hint. - let date = hint == Hint::Default && matches!(self.heap.object(o).map(|ob| &ob.class), Some(Class::Date(_))); + // Without a hint, a Date object converts as with the String hint. In a realm with + // `Options::es2015`, `Date.prototype[@@toPrimitive]` picks that order for a Date instead, + // and OrdinaryToPrimitive treats a missing hint as the Number hint (ECMA-262 11th edition, + // sections 7.1.1.1 and 20.4.4.45). + let date = hint == Hint::Default && !self.options.es2015 && matches!(self.heap.object(o).map(|ob| &ob.class), Some(Class::Date(_))); let order = if hint == Hint::String || date { ["toString", "valueOf"] } else { ["valueOf", "toString"] }; for name in order { let f = self.get_from(o, &key(name), v)?; diff --git a/crates/js/src/lib.rs b/crates/js/src/lib.rs index 4cdb639c85..4b02563e08 100644 --- a/crates/js/src/lib.rs +++ b/crates/js/src/lib.rs @@ -53,8 +53,10 @@ //! `hasInstance`, `toPrimitive` and `toStringTag` with the hooks ToPrimitive, `instanceof` and //! `Object.prototype.toString` read, Symbol-keyed properties with `Object.getOwnPropertySymbols`, //! and iterator objects with a `next` method from `Array.prototype.values`, `keys`, `entries` and -//! `@@iterator`, `String.prototype[@@iterator]` (by code point) and every `arguments` object. A -//! Symbol converted to a string or a number without `String(symbol)` or `toString` throws a +//! `@@iterator`, `String.prototype[@@iterator]` (by code point) and every `arguments` object. +//! `Date.prototype[@@toPrimitive]` converts a Date without a hint as with the String hint, and an +//! object without an `@@toPrimitive` method, a Date included, converts without a hint as with the +//! Number hint. A Symbol converted to a string or a number without `String(symbol)` or `toString` throws a //! `TypeError`. A string converts to a number in the `0b` and `0o` forms as well. Every iterator //! step and every prototype a Symbol-keyed lookup passes takes fuel, and every Symbol and registry //! entry counts against the heap limit. diff --git a/crates/js/src/symbol.rs b/crates/js/src/symbol.rs index 34fd489fa3..e89bbeb9f4 100644 --- a/crates/js/src/symbol.rs +++ b/crates/js/src/symbol.rs @@ -239,10 +239,10 @@ impl Interp { Value::Symbol(s) => f(self, PropKey::Sym(s.clone())), Value::Object(_) => { let p = self.to_primitive(v, Hint::String)?; - if let Value::Symbol(s) = p { - return f(self, PropKey::Sym(s)); - } - self.rooted(std::slice::from_ref(&p), |i| i.with_key(&p, |i, k| f(i, PropKey::Str(k)))) + self.rooted(std::slice::from_ref(&p), |i| match &p { + Value::Symbol(s) => f(i, PropKey::Sym(s.clone())), + _ => i.with_key(&p, |i, k| f(i, PropKey::Str(k))), + }) } _ => self.with_key(v, |i, k| f(i, PropKey::Str(k))), } diff --git a/crates/js/src/symbol_tests.rs b/crates/js/src/symbol_tests.rs index 5e372bdafd..a11c105107 100644 --- a/crates/js/src/symbol_tests.rs +++ b/crates/js/src/symbol_tests.rs @@ -241,6 +241,71 @@ fn json_calls_the_to_primitive_method_of_a_wrapper() { truth(&format!("var w = new String('x'); {hook} JSON.stringify({{a: 1, b: 2}}, [w]) === '{{\"b\":2}}'")); truth(&format!("var w = new Number(5); {hook} JSON.stringify([w], null, w) === '[\\n 2\\n]'")); truth("JSON.stringify([new String('x'), new Number(1)], null, new Number(1)) === '[\\n \"x\",\\n 1\\n]'"); + // A `@@toPrimitive` getter that deletes the prototype's method and gives `undefined` sends the + // lookup on to `Object.prototype`. + let getter = |method: &str| { + format!( + "Object.defineProperty(w, Symbol.toPrimitive, {{ get: function () {{ delete Object.getPrototypeOf(w).{method}; return undefined; }} }});" + ) + }; + let over = "Object.prototype.toString = function () { return '7'; };"; + truth(&format!("var w = new String('x'); {over} {} JSON.stringify(w) === '\"7\"'", getter("toString"))); + truth(&format!("var w = new Number(3); {over} delete Number.prototype.toString; {} JSON.stringify(w) === '7'", getter("valueOf"))); +} + +#[test] +fn a_symbol_key_from_to_primitive_counts_against_the_heap_while_the_property_is_used() { + // `mk(n)` makes a string of `n` units. The key's accessor deletes itself from + // `Object.prototype`, so when the key is a Symbol only the read or write holds it and its + // description of 2,000,000 units, and then makes a string of 1,500,000 units. With `keep` + // (1,000,000 units) and a description still counted, that string does not fit; without one it + // does. + let src = |key: &str, access: &str| { + format!( + "function mk(n) {{ return new Array(n + 1).join('x'); }} \ + var keep = mk(1000000), made = null; \ + function use() {{ var p = Object.prototype; delete p[Object.getOwnPropertySymbols(p)[0] || 'k']; \ + made = mk(1500000); return 0; }} \ + var w = {{}}; w[Symbol.toPrimitive] = function () {{ var k = {key}; \ + Object.defineProperty(Object.prototype, k, {{ configurable: true, get: use, set: use }}); return k; }}; \ + {access}; made.length" + ) + }; + let limits = || Limits { heap_bytes: 8 << 20, fuel: 50_000_000, ..Limits::default() }; + for access in ["({})[w]", "({})[w] = 1", "({})[w]++"] { + // A name as the key leaves the Symbol and its description to the collector, and the string + // fits. + assert_eq!(es2015(limits()).run(&src("(Symbol(mk(2000000)), 'k')", access)), Ok(JsValue::Number(1_500_000.0)), "{access}"); + match es2015(limits()).run(&src("Symbol(mk(2000000))", access)) { + Err(RunError { kind: RunErrorKind::Limit(LimitKind::Heap), .. }) => {} + other => panic!("{access}: {other:?}"), + } + } +} + +#[test] +fn date_objects_convert_through_their_to_primitive_method() { + let date = "var d = new Date(0); d.valueOf = function () { return 7; }; d.toString = function () { return 'date'; };"; + truth(&format!("{date} d + 1 === 'date1' && d * 1 === 7 && String(d) === 'date' && (d == 'date')")); + // Without a method, a Date converts with `valueOf` first when no hint is given. + // The inherited method is read-only, so an assignment does not shadow it. + truth(&format!("{date} d[Symbol.toPrimitive] = null; d + 1 === 'date1'")); + truth(&format!("{date} Object.defineProperty(d, Symbol.toPrimitive, {{ value: null }}); d + 1 === 8")); + truth(&format!("{date} Object.defineProperty(d, Symbol.toPrimitive, {{ value: undefined }}); d + 1 === 8 && String(d) === 'date'")); + truth(&format!("{date} delete Date.prototype[Symbol.toPrimitive]; d + 1 === 8 && d == 7")); + // The method itself, on any object. + truth( + "var m = Date.prototype[Symbol.toPrimitive], p = Object.getOwnPropertyDescriptor(Date.prototype, Symbol.toPrimitive); \ + typeof m === 'function' && m.length === 1 && !p.writable && !p.enumerable && p.configurable", + ); + let o = "var o = { valueOf: function () { return 7; }, toString: function () { return 's'; } }, m = Date.prototype[Symbol.toPrimitive];"; + truth(&format!("{o} m.call(o, 'number') === 7 && m.call(o, 'string') === 's' && m.call(o, 'default') === 's'")); + for call in ["m.call(o)", "m.call(o, 'other')", "m.call(o, new String('number'))", "m.call(1, 'number')", "m.call(o, 'defaultx')"] { + throws(&format!("{o} {call}"), "TypeError"); + } + // A realm without the option keeps the String-hint order for a Date. + let src = format!("{date} d + 1 === 'date1' && d * 1 === 7"); + assert_eq!(Realm::with_options(Options::default(), Limits::default()).run(&src), Ok(JsValue::Bool(true))); } #[test] diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 2579945202..48ce92a005 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1082,7 +1082,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - `vectorcraft-js` provides the ECMAScript 5.1 built-ins `Object` with its property-descriptor functions, `create`, `keys`, `seal` and `freeze` (section 15.2), `Function.prototype.bind` (15.3.4.5), `Array` with every ES5 method (15.4), the error types (15.11), `Math` (15.8), `JSON` with revivers, replacers and indentation (15.12), and the global functions with Annex B's `escape` and `unescape` (15.1, B.2). The array methods work on array-like objects. A method visits only the indices that exist when its range is longer than 4,096 indices and more than 8 times the properties on the object and its prototypes, so `new Array(4294967295).join("")` ends at once; a shorter range is visited index by index, holes included, and each index takes fuel. `join` writes a cycle back to an array as an empty string, `JSON.stringify` throws a `TypeError` on a cycle, and deep `JSON` nesting uses no native stack. Every loop takes fuel and every result is checked against the heap limit. `cargo xtask test262` runs the suite's ES5 built-in tests that need only these built-ins: 6,798 of 6,866 runs pass (the 34 failing tests expect rules of later editions). It also fetches the `json2.js` polyfill at a pinned commit and checks that its `stringify` and `parse` agree with the built-in `JSON`. Tests: `crates/js/src/builtins_tests.rs`, `crates/js/tests/test262.rs`, `crates/js/tests/json2.rs`. - `vectorcraft-js` has `String`, `Number`, `RegExp` and `Date` as ECMAScript 5.1 defines them (sections 15.5, 15.7, 15.9 and 15.10, https://262.ecma-international.org/5.1/), with Annex B's `substr`, `getYear`, `setYear` and `toGMTString`. `toFixed`, `toExponential` and `toPrecision` format a number from its exact decimal value, and `toString(radix)` writes any base from 2 to 36. Regular expressions (flags `g`, `i` and `m`) run on a backtracking matcher whose choice points and capture state count against the heap limit and which takes fuel for every step, so a catastrophic pattern stops at the fuel limit and 50,000 nested groups give a `SyntaxError` at the default depth limit. A string method that would build a string past the heap limit stops before it allocates. `Date` reads the clock and time zone the host sets (`Realm::set_clock`, `Realm::set_time_zone`; local time is UTC by default). `cargo xtask test262` runs the suite's `built-ins` tests for the four (https://github.com/tc39/test262): of the runs of the ES5 tests that need only the built-ins present, 1,379 of 1,411 pass for `String`, 298 of 298 for `Number`, 954 of 988 for `RegExp` and 8 of 8 for `Date`. The others expect later editions' rules (built-in functions whose `length` can be deleted, flags given with a RegExp object, a negative `lastIndex`, `RegExp.prototype` as a plain object, and `RegExp.prototype`'s `global`, `ignoreCase` and `multiline` properties that can be deleted). Tests: `crates/js/src/text_tests.rs`, `crates/js/tests/test262.rs`. - `cargo xtask test262` also reads the suite's Annex B tests (https://tc39.es/ecma262/#sec-additional-ecmascript-features-for-web-browsers), whichever edition they name. It parses the 819 tests under `test/annexB/language` without a feature tag in the modes their flags give, so a `for`-`in` variable with an initializer must parse in sloppy code and give a `SyntaxError` in strict code (682 of 843 runs pass), and it runs those tests and the `test/annexB/built-ins` tests for `String`, `Date`, `RegExp` and `Function` that need only the built-ins present (263 of 667 runs pass for the language tests and 56 of 252 for the built-ins). Failures go to `annexb-parse-failures.txt`, `annexb-language-failures.txt` and `annexb-builtins-failures.txt` beside the suite. A conformance failure does not fail the tests, but an interpreter panic fails `annex_b_runs`, so `cargo xtask test262` exits non-zero. A folder or file the runner cannot read also fails the test that reads it. The runner reads only regular files inside the suite, up to 8 MiB each, and does not follow symbolic links. Tests: `crates/js/tests/test262.rs`. - - With `Options::es2015` set, which it is not by default, a `vectorcraft-js` realm also has `Symbol` (ECMA-262 11th edition, section 19.4, https://262.ecma-international.org/11.0/): `Symbol(description)`, which `new` refuses with a `TypeError`, the `description` getter, `toString`, `valueOf`, and `Symbol.for` and `Symbol.keyFor` over a registry that lasts as long as the realm. `typeof` gives `"symbol"`. Symbols are property keys: `Object.getOwnPropertySymbols` lists an object's Symbol keys in the order they were added, `Object.defineProperty`, `getOwnPropertyDescriptor`, `freeze`, `seal`, `in`, `delete` and `hasOwnProperty` take them, and `for`-`in`, `Object.keys`, `Object.getOwnPropertyNames` and `JSON.stringify` leave them out. `String(symbol)` and `symbol.toString()` give `Symbol(description)`; any other conversion of a Symbol to a string or a number, such as `Symbol() + ''`, throws a `TypeError`. A string such as `'0b10'` or `'0o2'` converts to a number, as section 7.1.3.1 gives. The well-known Symbols `Symbol.iterator`, `Symbol.asyncIterator`, `Symbol.hasInstance`, `Symbol.toPrimitive` and `Symbol.toStringTag` are defined: conversion to a primitive calls an object's `@@toPrimitive` method, `instanceof` calls the right side's `@@hasInstance` method, and `Object.prototype.toString` writes a string `@@toStringTag`; `JSON.stringify` calls a String or Number object's `@@toPrimitive` method too. Nothing reads `Symbol.asyncIterator` yet. `Array.prototype.values` (also `Array.prototype[Symbol.iterator]`), `keys` and `entries`, `String.prototype[Symbol.iterator]` and every `arguments` object's `Symbol.iterator` return iterators whose `next()` gives `{value, done}` objects; a string iterator steps by code point and keeps a surrogate pair together. An array iterator reads the `length` at each step, so it visits elements added during the walk. Each step takes fuel, as does each prototype a Symbol-keyed lookup passes, and each Symbol and registry entry counts against the heap limit. A realm without the option, including the one the app runs scripts in, has none of these names, and a host function that returns a Symbol there throws a `TypeError`. The language does not have `for`-`of`, spread or destructuring yet, so scripts call `next()` themselves. `cargo xtask test262` runs the suite's tests of `Symbol`, `ArrayIteratorPrototype`, `StringIteratorPrototype`, `Object.getOwnPropertySymbols`, `Array.prototype.values`, `keys`, `entries` and `Symbol.iterator`, and `String.prototype[Symbol.iterator]` that need only these built-ins and parse as ES5, in such a realm: 164 of 216 runs pass (6 passed before), and the 52 others expect a configurable function `length` and a function `name` property. Tests: `crates/js/src/symbol_tests.rs`, `crates/js/tests/test262.rs`. + - With `Options::es2015` set, which it is not by default, a `vectorcraft-js` realm also has `Symbol` (ECMA-262 11th edition, section 19.4, https://262.ecma-international.org/11.0/): `Symbol(description)`, which `new` refuses with a `TypeError`, the `description` getter, `toString`, `valueOf`, and `Symbol.for` and `Symbol.keyFor` over a registry that lasts as long as the realm. `typeof` gives `"symbol"`. Symbols are property keys: `Object.getOwnPropertySymbols` lists an object's Symbol keys in the order they were added, `Object.defineProperty`, `getOwnPropertyDescriptor`, `freeze`, `seal`, `in`, `delete` and `hasOwnProperty` take them, and `for`-`in`, `Object.keys`, `Object.getOwnPropertyNames` and `JSON.stringify` leave them out. `String(symbol)` and `symbol.toString()` give `Symbol(description)`; any other conversion of a Symbol to a string or a number, such as `Symbol() + ''`, throws a `TypeError`. A string such as `'0b10'` or `'0o2'` converts to a number, as section 7.1.3.1 gives. The well-known Symbols `Symbol.iterator`, `Symbol.asyncIterator`, `Symbol.hasInstance`, `Symbol.toPrimitive` and `Symbol.toStringTag` are defined: conversion to a primitive calls an object's `@@toPrimitive` method, `instanceof` calls the right side's `@@hasInstance` method, and `Object.prototype.toString` writes a string `@@toStringTag`; `JSON.stringify` calls a String or Number object's `@@toPrimitive` method too. `Date.prototype[Symbol.toPrimitive]` (section 20.4.4.45) converts a Date with `toString` first for the hints `"string"` and `"default"` and with `valueOf` first for `"number"`, so `date + 1` joins the date's string; an object without an `@@toPrimitive` method, a Date whose method is `null` included, tries `valueOf` first when no hint is given. Nothing reads `Symbol.asyncIterator` yet. `Array.prototype.values` (also `Array.prototype[Symbol.iterator]`), `keys` and `entries`, `String.prototype[Symbol.iterator]` and every `arguments` object's `Symbol.iterator` return iterators whose `next()` gives `{value, done}` objects; a string iterator steps by code point and keeps a surrogate pair together. An array iterator reads the `length` at each step, so it visits elements added during the walk. Each step takes fuel, as does each prototype a Symbol-keyed lookup passes, and each Symbol and registry entry counts against the heap limit. A realm without the option, including the one the app runs scripts in, has none of these names, and a host function that returns a Symbol there throws a `TypeError`. The language does not have `for`-`of`, spread or destructuring yet, so scripts call `next()` themselves. `cargo xtask test262` runs the suite's tests of `Symbol`, `ArrayIteratorPrototype`, `StringIteratorPrototype`, `Object.getOwnPropertySymbols`, `Array.prototype.values`, `keys`, `entries` and `Symbol.iterator`, and `String.prototype[Symbol.iterator]` that need only these built-ins and parse as ES5, in such a realm: 164 of 216 runs pass (6 passed before), and the 52 others expect a configurable function `length` and a function `name` property. Tests: `crates/js/src/symbol_tests.rs`, `crates/js/tests/test262.rs`. - Scripts: `cargo xtask corpus --scripts` fetches 397 public scripts and 1 file they include from 19 MIT and Apache-2.0 repositories at pinned commits into `corpus/scripts` (gitignored), each repository's license file beside its scripts. `xtask/script-corpus.txt` lists every file with its size and SHA-256, and a download is checked against both before it replaces anything; one more candidate is left out because it is over the 1 MiB limit for one script. `cargo xtask scripts --pass-rate [--report ]` runs each script headless in a process of its own (a new document, 5,000,000 instructions, no dialog answers, file reads only in its repository's folder and a new folder of its own, file writes only in that folder, no command it can start, stopped after 10 seconds) and writes a JSON report: the pass rate overall, per repository and for the scripts without dialogs or windows, how many parse, and each script's outcome. Script failures never fail the command, and without the corpus it skips. These limits are VectorCraft's own. Tests: `xtask/src/script_corpus.rs`, `crates/engine/tests/script_corpus.rs`. - With `Options::e4x` set, an E4X name standing alone (`@a`, `@ns::a`, `@[expr]`, `ns::a`, `*`) inside `with` or a filter predicate can be assigned, with `=` or a compound operator, incremented, decremented, deleted and used as a `for` or `for each` variable, as well as read. Each of these uses the nearest XML or XMLList value in scope that holds the name and evaluates the name once. When no XML value in scope holds the name, the read or write throws a `ReferenceError` before the right-hand side runs and creates no child or attribute, as ECMA-357 section 11.1 (https://ecma-international.org/publications-and-standards/standards/ecma-357/) specifies, so a filter such as `list.(@id == '1')` throws when an item has no `@id` and no outer XML value holds one. Tests: `crates/js/src/xml_tests.rs`. - `vectorcraft-js` runs ECMAScript for XML (ECMA-357, 2nd edition, https://ecma-international.org/publications-and-standards/standards/ecma-357/) when `Options::e4x` is set, which it is not by default: XML and XMLList literals with embedded `{}` expressions, the `..`, `.@`, `.*`, `.()` and `::` selectors, assignment and `delete` on selected nodes, `for each`, `default xml namespace`, and the `XML`, `XMLList`, `Namespace` and `QName` objects with their methods and settings. `xml.xpath(expression[, variables])` evaluates an XPath 1.0 expression (https://www.w3.org/TR/1999/REC-xpath-19991116/) with all 13 axes and the 27 core functions, and returns the selected nodes as an XMLList in document order without repeats. Each property of `variables` binds the variable of its name, an XMLList runs the expression on each of its elements in turn, and a prefix in a name test resolves through the context element's in-scope namespaces. An expression that breaks the grammar gives a `SyntaxError`; an unknown function, a wrong argument count, an unbound prefix or variable, and a result that is not a node-set or that holds the root or a namespace node give a `TypeError`. `id()` selects nothing, and evaluation uses no native stack, takes fuel and counts against the heap limit. `` in an XML string gives a `SyntaxError`. An XML declaration at the start of an XML string, after optional white space, is checked against XML 1.0's grammar (https://www.w3.org/TR/xml/#NT-XMLDecl): a version of `1.` and digits, then an optional encoding name and an optional standalone `yes` or `no`, in that order; any other declaration, or one with a character XML does not allow, gives a `SyntaxError`. The parser takes fuel for the length of every name, white space run and declaration it scans, and for the text it searched when a quote, CDATA section, comment or processing instruction is not closed. Parsing, serializing, comparing and copying trees use no native stack, and each takes fuel and counts against the heap limit. Inserting a node into itself or its descendants throws a `TypeError` before the tree changes, a literal or XML string nested past `Options::max_depth` gives a `SyntaxError`, and a tree built past that depth stops at the heap limit. Tests: `crates/js/src/xml_tests.rs`. From 93df144331b105009fc7fe966abd3bd8641079e5 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 22 Nov 2026 02:35:00 -0800 Subject: [PATCH 052/151] JavaScript: keep Symbol keys and converted operands counted while script runs Object.defineProperties and Object.create now keep the Symbol keys of the properties object rooted until they are defined, so a getter that deletes a Symbol-keyed property already read no longer lets a collection drop the Symbol's description from the heap count. The + operator and the relational comparisons now keep the first operand's converted value rooted while the second operand's @@toPrimitive or valueOf runs, so a fresh Symbol or string from the first conversion stays counted against the heap limit. --- crates/js/src/builtins/object.rs | 10 ++++++- crates/js/src/interp.rs | 9 ++++-- crates/js/src/symbol_tests.rs | 51 ++++++++++++++++++++++++++++++++ 3 files changed, 66 insertions(+), 4 deletions(-) diff --git a/crates/js/src/builtins/object.rs b/crates/js/src/builtins/object.rs index 48fdbb6eda..42947c7d7a 100644 --- a/crates/js/src/builtins/object.rs +++ b/crates/js/src/builtins/object.rs @@ -198,7 +198,15 @@ fn define_all(interp: &mut Interp, o: ObjId, props: &Value) -> JsResult<()> { interp.temp_roots.push(Value::Object(p)); let r = (|| { let mut descs = Vec::new(); - for k in own_prop_keys(interp, p)? { + let keys = own_prop_keys(interp, p)?; + // A getter can delete a Symbol-keyed property already read, so the Symbols stay rooted + // until they are defined on `o`. + for k in &keys { + if let PropKey::Sym(s) = k { + interp.temp_roots.push(Value::Symbol(s.clone())); + } + } + for k in keys { interp.use_fuel()?; if !interp.get_own_pk(p, &k)?.is_some_and(|prop| prop.enumerable()) { continue; diff --git a/crates/js/src/interp.rs b/crates/js/src/interp.rs index 3c6f73cb64..405874dc96 100644 --- a/crates/js/src/interp.rs +++ b/crates/js/src/interp.rs @@ -2993,7 +2993,8 @@ impl Interp { return self.xml_concat(a, b); } let pa = self.to_primitive(a, Hint::Default)?; - let pb = self.to_primitive(b, Hint::Default)?; + // The right side's conversion can run script, so the left side's result stays counted. + let pb = self.rooted(std::slice::from_ref(&pa), |i| i.to_primitive(b, Hint::Default))?; if matches!(pa, Value::String(_)) || matches!(pb, Value::String(_)) { // Both are primitives, so this converts them without running script code; a Symbol // throws. @@ -3007,12 +3008,14 @@ impl Interp { /// The abstract relational comparison `x < y` (section 11.8.5): `None` when either side is /// NaN. fn less_than(&mut self, x: &Value, y: &Value, left_first: bool) -> JsResult> { + // The second conversion can run script, so the first one's result stays counted. let (px, py) = if left_first { let px = self.to_primitive(x, Hint::Number)?; - (px, self.to_primitive(y, Hint::Number)?) + let py = self.rooted(std::slice::from_ref(&px), |i| i.to_primitive(y, Hint::Number))?; + (px, py) } else { let py = self.to_primitive(y, Hint::Number)?; - (self.to_primitive(x, Hint::Number)?, py) + (self.rooted(std::slice::from_ref(&py), |i| i.to_primitive(x, Hint::Number))?, py) }; if let (Value::String(a), Value::String(b)) = (&px, &py) { // Both stay rooted, so the first copy is still counted while the second is made. diff --git a/crates/js/src/symbol_tests.rs b/crates/js/src/symbol_tests.rs index a11c105107..6ea28e1dee 100644 --- a/crates/js/src/symbol_tests.rs +++ b/crates/js/src/symbol_tests.rs @@ -283,6 +283,57 @@ fn a_symbol_key_from_to_primitive_counts_against_the_heap_while_the_property_is_ } } +#[test] +fn define_properties_keeps_a_symbol_key_counted_after_a_getter_deletes_it() { + // The second Symbol-keyed descriptor's getter deletes the first property, drops `s` and makes + // a string of 1,500,000 units. With `keep` (1,000,000 units) and the first Symbol's + // description of 2,000,000 units still counted, that string does not fit; with a short + // description it does. + let src = |description: &str, define: &str| { + format!( + "function mk(n) {{ return new Array(n + 1).join('x'); }} \ + var keep = mk(1000000), made = null, s = Symbol({description}), props = {{}}; \ + props[s] = {{ value: 1, enumerable: true }}; \ + Object.defineProperty(props, Symbol('t'), {{ enumerable: true, get: function () {{ \ + delete props[s]; s = null; made = mk(1500000); return {{ value: 2 }}; }} }}); \ + var o = {define}; o[Object.getOwnPropertySymbols(o)[0]] + ' ' + made.length" + ) + }; + let limits = || Limits { heap_bytes: 8 << 20, fuel: 50_000_000, ..Limits::default() }; + for define in ["Object.defineProperties({}, props)", "Object.create(null, props)"] { + assert_eq!(es2015(limits()).run(&src("'d'", define)), Ok(JsValue::String("1 1500000".into())), "{define}"); + match es2015(limits()).run(&src("mk(2000000)", define)) { + Err(RunError { kind: RunErrorKind::Limit(LimitKind::Heap), .. }) => {} + other => panic!("{define}: {other:?}"), + } + } +} + +#[test] +fn an_operator_keeps_the_first_operand_converted_while_it_converts_the_second() { + // `a` converts to a Symbol with a description of 2,000,000 units that nothing else holds, and + // `b`'s conversion makes a string of 1,500,000 units. With `keep` (1,000,000 units) and the + // description still counted, that string does not fit; when `a` gives a number it does. + let src = |first: &str, op: &str| { + format!( + "function mk(n) {{ return new Array(n + 1).join('x'); }} \ + var keep = mk(1000000), made = null; \ + var a = {{}}; a[Symbol.toPrimitive] = function () {{ return {first}; }}; \ + var b = {{}}; b[Symbol.toPrimitive] = function () {{ made = mk(1500000); return 1; }}; \ + try {{ a {op} b; }} catch (e) {{ if (!(e instanceof TypeError)) throw e; }} \ + made.length === 1500000" + ) + }; + let limits = || Limits { heap_bytes: 8 << 20, fuel: 50_000_000, ..Limits::default() }; + for op in ["+", "<", ">", "<=", ">="] { + assert_eq!(es2015(limits()).run(&src("(Symbol(mk(2000000)), 0)", op)), Ok(JsValue::Bool(true)), "{op}"); + match es2015(limits()).run(&src("Symbol(mk(2000000))", op)) { + Err(RunError { kind: RunErrorKind::Limit(LimitKind::Heap), .. }) => {} + other => panic!("{op}: {other:?}"), + } + } +} + #[test] fn date_objects_convert_through_their_to_primitive_method() { let date = "var d = new Date(0); d.valueOf = function () { return 7; }; d.toString = function () { return 'date'; };"; From 35ee5de2d480bb4909a7705ab50a188deb183e99 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 22 Nov 2026 03:24:32 -0800 Subject: [PATCH 053/151] Place: an empty password counts as none, as file.place reads it file.place reads an empty password as no password, but the PDF Text preference treated one as given: a PDF placed from a path with Link on and password "" got textAs outlines and was embedded instead of linked. With Show Import Options off, an encrypted PDF placed with an empty password was not asked for its password and the place failed. Both checks now use the same test as the engine and the dialog's own password field. Tests cover the linked place with an empty password and the password prompt for an encrypted PDF. --- crates/ui-egui/src/dialogs/import_pdf.rs | 13 +++++++---- .../ui-egui/src/dialogs/tests_import_pdf.rs | 23 +++++++++++++++++++ 2 files changed, 32 insertions(+), 4 deletions(-) diff --git a/crates/ui-egui/src/dialogs/import_pdf.rs b/crates/ui-egui/src/dialogs/import_pdf.rs index c28f5694f6..fe4603ccf0 100644 --- a/crates/ui-egui/src/dialogs/import_pdf.rs +++ b/crates/ui-egui/src/dialogs/import_pdf.rs @@ -190,11 +190,11 @@ pub fn offer_place(app: &mut VectorcraftApp, p: &Value) -> bool { } /// [`offer_place`] when Show Import Options is off: asks (true) only for the password of an -/// encrypted PDF given no `password`, which nothing else opens, and places its first page (or +/// encrypted PDF given no `password` (or an empty one), which nothing else opens, and places its first page (or /// `page`) and crop box once it is unlocked; any other PDF is placed that way without asking. pub fn offer_place_password(app: &mut VectorcraftApp, p: &Value) -> bool { // A `page` that isn't a page number is left for `file.place` to refuse. - if p.get("password").is_some() || p.get("page").is_some_and(|v| v.as_u64().is_none_or(|n| n == 0)) { + if password_given(p) || p.get("page").is_some_and(|v| v.as_u64().is_none_or(|n| n == 0)) { return false; } let Some((name, bytes, path)) = place_source(app, p, |ext| matches!(ext, "pdf" | "ai" | "ait")) else { return false }; @@ -233,6 +233,11 @@ fn password(d: &Dialog) -> Option { Some(d.str("password")).filter(|p| !p.is_empty()) } +/// Do the `file.place` params `p` give a password: `file.place` reads an empty one as none. +fn password_given(p: &Value) -> bool { + p.get("password").is_some_and(|v| !v.is_null() && v.as_str() != Some("")) +} + /// The labels of the Text choices, in the order of [`TextAs::ALL`]. const TEXT_AS_LABELS: [&str; 2] = ["Editable", "Outlines"]; @@ -264,7 +269,7 @@ pub(crate) fn with_preferred_text_as(app: &VectorcraftApp, name: &str, bytes: &[ p } -/// The `file.place` params `p` of a PDF placed embedded (Link off, from bytes or with a password), +/// The `file.place` params `p` of a PDF placed embedded (Link off, from bytes or with a non-empty password), /// by the user or as a command, get the `pdfTextAs` preference as their `textAs` when it is Outlines and they have no /// `textAs`. A linked page shows the file's own text, and a `.ai` or `.ait` file is placed as it /// says. @@ -272,7 +277,7 @@ pub(crate) fn place_with_preferred_text_as(app: &VectorcraftApp, p: &mut Value) let given = |k: &str| p.get(k).is_some_and(|v| !v.is_null()); let path = p.get("path").and_then(Value::as_str); let name = path.or_else(|| p.get("name").and_then(Value::as_str)).unwrap_or_default(); - let linked = path.is_some() && p.get("link").and_then(Value::as_bool) != Some(false) && !given("password"); + let linked = path.is_some() && p.get("link").and_then(Value::as_bool) != Some(false) && !password_given(p); if given("textAs") || linked || preferred_text_as(app) == TextAs::Text || fileio::extension(name) != "pdf" { return; } diff --git a/crates/ui-egui/src/dialogs/tests_import_pdf.rs b/crates/ui-egui/src/dialogs/tests_import_pdf.rs index a1e9a350a4..6e234bbd0c 100644 --- a/crates/ui-egui/src/dialogs/tests_import_pdf.rs +++ b/crates/ui-egui/src/dialogs/tests_import_pdf.rs @@ -521,7 +521,30 @@ fn file_place_without_the_dialog_takes_the_pdf_text_preference() { let placed = st.doc.node(st.selection.objects[0]).unwrap(); assert!(matches!(placed.kind, NodeKind::PlacedDocument(_)), "linked: {:?}", placed.kind); + // `file.place` reads an empty password as none, so the page stays linked. + crate::place::run(&mut app, &json!({"path": path, "password": "", "showImportOptions": false})).unwrap(); + let st = app.session.active().unwrap(); + let placed = st.doc.node(st.selection.objects[0]).unwrap(); + assert!(matches!(placed.kind, NodeKind::PlacedDocument(_)), "an empty password: linked: {:?}", placed.kind); + set_pdf_text(&mut app, "text"); crate::place::run(&mut app, &embedded).unwrap(); assert_eq!(type_objects(&app), 2, "Editable: page 1's type object"); } + +/// With Show Import Options off, an encrypted PDF placed with an empty `password` asks for its +/// password, as one placed without a `password` does. +#[test] +fn an_empty_password_asks_for_the_password_of_an_encrypted_pdf() { + let mut app = app(); + let bytes = pdf(&[PdfPage::new(120.0, 60.0, "1 0 0 rg 0 0 20 20 re f")], Some("pw")); + place(&mut app, &bytes, json!({"password": "", "showImportOptions": false})).unwrap(); + assert_eq!((field(&app, "__locked"), field(&app, "__passwordOnly")), (json!(true), json!(true))); + frame(&mut app); + set(&mut app, "password", json!("pw")); + confirm(&mut app).unwrap(); + assert!(app.ui.dialog.is_none()); + let st = app.session.active().unwrap(); + let b = st.doc.node(st.selection.objects[0]).and_then(|n| n.geometric_bounds()).unwrap(); + assert!((b.width() - 120.0).abs() < 0.01, "placed once unlocked: {}", b.width()); +} From 45286143243518c81f356495ee009aa7a0dc5843 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 22 Nov 2026 04:14:12 -0800 Subject: [PATCH 054/151] Canvas: a still release sends the tool its changed modifiers and Space A tool drag released without moving since its last frame sent only the up, so Shift pressed in the release's frame did not constrain the shape it committed. The release now also sends a drag when Shift, Alt, Cmd/Ctrl, Space or Backtick changed since the drag's last frame, as a held drag does. Space at the release is now read at the button-up, as the other modifiers are: Space pressed after the release in the same frame no longer moves the shape, and a focus loss after the release keeps Space as it was held. --- crates/ui-egui/src/canvas/drag.rs | 24 +++++++- crates/ui-egui/src/canvas/input.rs | 30 ++++++---- crates/ui-egui/src/canvas/tests.rs | 92 ++++++++++++++++++++++++++++++ 3 files changed, 133 insertions(+), 13 deletions(-) diff --git a/crates/ui-egui/src/canvas/drag.rs b/crates/ui-egui/src/canvas/drag.rs index 512df6e9a9..45b474c6d4 100644 --- a/crates/ui-egui/src/canvas/drag.rs +++ b/crates/ui-egui/src/canvas/drag.rs @@ -109,6 +109,18 @@ pub(super) fn backquote_seen(ui: &Ui) -> (bool, Option) { (now, before) } +/// Whether Space was held at the end of the frame before (`None` before the first), recording +/// whether it is held now. The canvas records it once a frame, as it does Backtick ([`backquote_seen`]). +pub(super) fn space_seen(ui: &Ui) -> Option { + let id = egui::Id::unique("canvas-space-seen"); + let now = ui.input(|i| i.key_down(egui::Key::Space)); + ui.data_mut(|d| { + let before = d.get_temp::(id); + d.insert_temp(id, now); + before + }) +} + /// Whether Backtick was held when `button` went up in this frame, with `before` its state at the end /// of the frame before ([`backquote_seen`]). Its state as the frame began is the opposite of its /// first press or release in the frame; when the window lost the focus first (which lets go of every @@ -116,11 +128,17 @@ pub(super) fn backquote_seen(ui: &Ui) -> (bool, Option) { /// releases and focus losses before the button-up then apply in the order they came. Without a /// button-up in this frame, its state now. pub(super) fn backquote_at_release(ui: &Ui, button: egui::PointerButton, before: Option) -> bool { + key_at_release(ui, egui::Key::Backtick, button, before) +} + +/// Whether `key` was held when `button` went up in this frame, by the rules of +/// [`backquote_at_release`], with `before` its state at the end of the frame before. +pub(super) fn key_at_release(ui: &Ui, key: egui::Key, button: egui::PointerButton, before: Option) -> bool { ui.input(|i| { - let now = i.key_down(egui::Key::Backtick); - // A press or release of Backtick (`Some(pressed)`), or a focus loss (`None`). + let now = i.key_down(key); + // A press or release of `key` (`Some(pressed)`), or a focus loss (`None`). let step = |e: &egui::Event| match e { - egui::Event::Key { key: egui::Key::Backtick, pressed, repeat: false, .. } => Some(Some(*pressed)), + egui::Event::Key { key: k, pressed, repeat: false, .. } if *k == key => Some(Some(*pressed)), egui::Event::WindowFocused(false) => Some(None), _ => None, }; diff --git a/crates/ui-egui/src/canvas/input.rs b/crates/ui-egui/src/canvas/input.rs index 67391b2e6e..5be38cd994 100644 --- a/crates/ui-egui/src/canvas/input.rs +++ b/crates/ui-egui/src/canvas/input.rs @@ -1,8 +1,8 @@ use super::artboards::{artboard_name_at, begin_artboard_name_edit, name_press_id, select_named_artboard}; use super::drag::{ FrameMove, HoverContext, apply_requests, backquote_at_release, backquote_seen, dispatch, drag_art_out, drag_id, drag_layer_id, drag_pos_id, - drop_press, mods, move_pose, on_canvas, pen_pose, pen_pressure, space_lends_view_tools, tool_drag_doc_id, tool_drag_mods_changed, - tool_drag_moved, tool_frame_moves, tool_holds, tool_press_doc_id, + drop_press, key_at_release, mods, move_pose, on_canvas, pen_pose, pen_pressure, space_lends_view_tools, space_seen, tool_drag_doc_id, + tool_drag_mods_changed, tool_drag_moved, tool_frame_moves, tool_holds, tool_press_doc_id, }; use super::view::{ HOLD_DELAY, HOLD_ZOOM, SCRUB_SLOP, SCRUB_ZOOM, WheelTurn, animated_zoom, edge_scroll, edge_scroll_pixels, pan_pixels, pan_ppp, rotate_about, @@ -30,7 +30,8 @@ pub(super) fn handle_input(app: &mut VectorcraftApp, ui: &Ui, resp: &egui::Respo let at = hover.or_else(|| pointer.interact_pos().filter(|p| rect.contains(*p))); let view = app.view_info(); let (backquote_now, backquote_before) = backquote_seen(ui); - let f = Pointing { resp, rect, pointer: &pointer, m, space, xf, v, view, backquote_before, modal }; + let space_before = space_seen(ui); + let f = Pointing { resp, rect, pointer: &pointer, m, space, xf, v, view, backquote_before, space_before, modal }; touch_gestures(app, ui, rect, view, modal); // Pressed and held still, a pen or a finger opens the context menu (egui's long touch): the // tool's press is dropped, as a right-click presses nothing. Under a modal dialog it drops nothing. @@ -139,9 +140,11 @@ pub(super) fn handle_input(app: &mut VectorcraftApp, ui: &Ui, resp: &egui::Respo if held { drag_held(app, ui, &f, d, p); } else { - // The drag ends where its button went up, with the modifiers held then: the moves and - // modifier changes after the release in this frame do not count. - let up = Pointing { m: release_mods(ui, button).unwrap_or(f.m), ..f }; + // The drag ends where its button went up, with the modifiers and Space held then: the + // moves and key changes after the release in this frame do not count. + let m = release_mods(ui, button).unwrap_or(f.m); + let space = space_lends_view_tools(app, m, key_at_release(ui, egui::Key::Space, button, f.space_before)); + let up = Pointing { m, space, ..f }; drag_released(app, ui, &up, d, release_pos(ui, button, false).unwrap_or(p)); } } else if let Some(p) = hover_tool @@ -224,6 +227,8 @@ struct Pointing<'a> { view: vectorcraft_engine::ViewInfo, /// Whether Backtick was held at the end of the frame before ([`backquote_seen`]). backquote_before: Option, + /// Whether Space was held at the end of the frame before ([`space_seen`]). + space_before: Option, /// Whether a modal dialog is open ([`crate::panel_docking::modal_open`]). modal: bool, } @@ -596,14 +601,17 @@ fn drag_released(app: &mut VectorcraftApp, ui: &Ui, f: &Pointing, d: Drag, p: Po let last_drag: Option = ui.data(|dd| dd.get_temp(tool_drag_doc_id())); // Where the pointer was in the frame before: a zoom marquee moved with Space follows it. let before: Option = ui.data(|dd| dd.get_temp(drag_pos_id())); + // Backtick as it was at the button-up: a key pressed or released later in the frame does not count. + let backquote = backquote_at_release(ui, egui::PointerButton::Primary, f.backquote_before); + // Whether Shift, Alt, Cmd/Ctrl, Space or Backtick changed since the drag's last frame, read + // before the drag's state is cleared below. + let mods_changed = matches!(d, Drag::Tool) && tool_drag_mods_changed(ui, mods(m, space), backquote); ui.data_mut(|dd| { dd.remove::(drag_id()); dd.remove::(drag_pos_id()); dd.remove::(tool_drag_doc_id()); dd.remove::(tool_press_doc_id()); }); - // Backtick as it was at the button-up: a key pressed or released later in the frame does not count. - let backquote = backquote_at_release(ui, egui::PointerButton::Primary, f.backquote_before); let ui_zoom = app.canvas_ui_zoom; match d { Drag::ZoomBox { start } => { @@ -640,12 +648,14 @@ fn drag_released(app: &mut VectorcraftApp, ui: &Ui, f: &Pointing, d: Drag, p: Po // (#834). Only once the press has dragged, so a click's jitter stays a click // (the Pen's corner anchor, no nudge with Direct Selection). A tool that builds a // stroke from the drag's samples gets the frame's other moves before it, up to the - // button-up: the moves after it are hover. + // button-up: the moves after it are hover. A modifier that changed at the release + // with the pointer held still reshapes the preview too, as it does while held + // (#4711): Shift pressed in the release's frame still draws a square. let (moves, last_pose) = tool_frame_moves(ui, app, true); let pen = move_pose(app, &xf, last_pose); if let Some(last) = last_drag { dispatch_frame_moves(app, ui, f, backquote, moves); - if last != xf.to_doc(p) { + if last != xf.to_doc(p) || mods_changed { let ev = PointerEvent { kind: PointerKind::Drag, pos: xf.to_doc(p), diff --git a/crates/ui-egui/src/canvas/tests.rs b/crates/ui-egui/src/canvas/tests.rs index cc4660f7bf..73b2d37547 100644 --- a/crates/ui-egui/src/canvas/tests.rs +++ b/crates/ui-egui/src/canvas/tests.rs @@ -1451,6 +1451,98 @@ fn tool_drag_ends_with_the_modifiers_of_its_button_release() { assert!((w - 2.0 * h).abs() < 1e-6, "Shift pressed after the release does not constrain, got {w} x {h}"); } +/// Shift pressed only in the frame of a tool drag's release, with the pointer held still since +/// the drag's last frame, still constrains the Rectangle tool's rectangle to a square. +#[test] +fn shift_pressed_at_a_still_release_constrains_the_tool_drag() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.session.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + app.select_tool("rectangle"); + let ctx = egui::Context::default(); + frame(&mut app, &ctx, vec![]); + let from = app.canvas_rect.unwrap().center() - vec2(30.0, 15.0); + let to = from + vec2(60.0, 30.0); + let b = |pos, pressed, modifiers| egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers }; + frame(&mut app, &ctx, vec![egui::Event::PointerMoved(from), b(from, true, egui::Modifiers::NONE)]); + frame(&mut app, &ctx, vec![egui::Event::PointerMoved(from + vec2(30.0, 15.0))]); + frame(&mut app, &ctx, vec![egui::Event::PointerMoved(to)]); + frame(&mut app, &ctx, vec![egui::Event::ModifiersChanged(egui::Modifiers::SHIFT), b(to, false, egui::Modifiers::SHIFT)]); + frame(&mut app, &ctx, vec![egui::Event::ModifiersChanged(egui::Modifiers::NONE)]); + let st = app.session.active().unwrap(); + let kids = st.doc.layers[0].children().unwrap(); + assert_eq!(kids.len(), 1, "the drag draws one rectangle"); + let r = kids[0].geometric_bounds().unwrap(); + let (w, h) = (r.width(), r.height()); + assert!((w - h).abs() < 1e-6, "Shift pressed at a still release draws a square, got {w} x {h}"); +} + +/// Space pressed after a tool drag's release, in the same frame, does not count for the drag: the +/// Rectangle tool's last move still resizes the rectangle instead of moving it. +#[test] +fn space_pressed_after_the_release_does_not_move_the_tool_drag() { + let draw = |space_after: bool| { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.session.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + app.select_tool("rectangle"); + let ctx = egui::Context::default(); + frame(&mut app, &ctx, vec![]); + let from = app.canvas_rect.unwrap().center() - vec2(30.0, 15.0); + let to = from + vec2(60.0, 30.0); + let b = |pos, pressed| egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers: egui::Modifiers::NONE }; + let space = + |pressed| egui::Event::Key { key: egui::Key::Space, physical_key: None, pressed, repeat: false, modifiers: egui::Modifiers::NONE }; + frame(&mut app, &ctx, vec![egui::Event::PointerMoved(from), b(from, true)]); + frame(&mut app, &ctx, vec![egui::Event::PointerMoved(from + vec2(30.0, 15.0))]); + let mut release = vec![egui::Event::PointerMoved(to), b(to, false)]; + if space_after { + release.push(space(true)); + } + frame(&mut app, &ctx, release); + frame(&mut app, &ctx, if space_after { vec![space(false)] } else { vec![] }); + let st = app.session.active().unwrap(); + let kids = st.doc.layers[0].children().unwrap(); + assert_eq!(kids.len(), 1, "the drag draws one rectangle"); + let r = kids[0].geometric_bounds().unwrap(); + (r.width(), r.height()) + }; + let plain = draw(false); + let (w, h) = draw(true); + assert!((w - plain.0).abs() < 1e-6 && (h - plain.1).abs() < 1e-6, "Space after the release keeps the size {plain:?}, got {w} x {h}"); +} + +/// Space held through a tool drag still counts at its release when the window loses the focus +/// after the release in the same frame: the Rectangle tool's last move still moves the rectangle. +#[test] +fn space_held_at_the_release_counts_when_the_focus_goes_after_it() { + let draw = |focus_lost: bool| { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.session.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + app.select_tool("rectangle"); + let ctx = egui::Context::default(); + frame(&mut app, &ctx, vec![]); + let from = app.canvas_rect.unwrap().center() - vec2(30.0, 15.0); + let to = from + vec2(60.0, 30.0); + let b = |pos, pressed| egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers: egui::Modifiers::NONE }; + let space = + |pressed| egui::Event::Key { key: egui::Key::Space, physical_key: None, pressed, repeat: false, modifiers: egui::Modifiers::NONE }; + frame(&mut app, &ctx, vec![egui::Event::PointerMoved(from), b(from, true)]); + frame(&mut app, &ctx, vec![egui::Event::PointerMoved(from + vec2(30.0, 15.0))]); + frame(&mut app, &ctx, vec![space(true)]); + let mut release = vec![egui::Event::PointerMoved(to), b(to, false)]; + release.push(if focus_lost { egui::Event::WindowFocused(false) } else { space(false) }); + frame(&mut app, &ctx, release); + frame(&mut app, &ctx, vec![]); + let st = app.session.active().unwrap(); + let kids = st.doc.layers[0].children().unwrap(); + assert_eq!(kids.len(), 1, "the drag draws one rectangle"); + let r = kids[0].geometric_bounds().unwrap(); + (r.x0, r.y0, r.width(), r.height()) + }; + let released = draw(false); + let lost = draw(true); + assert_eq!(lost, released, "a focus loss after the release keeps Space as held at the release"); +} + /// A press on an artboard's name starts no drag. Moving with the button still held is not hover, /// so Shift over a gridline intersection does not position the Perspective Selection tool's plane /// until the button is up. From cfb9f825683bfcd832a3c168cbf7d049a40685c2 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 22 Nov 2026 04:14:26 -0800 Subject: [PATCH 055/151] Place: PDF bytes without a .pdf name take the PDF Text preference The PDF Text preference decided whether a place was a PDF by the extension of its path or name, so a file.place with dataBase64 and no name, or a name with another extension, kept its type editable with Outlines set. file.place reads such bytes as a PDF by their content. Bytes now count as a PDF when they start with %PDF, as file.place detects them; only the first bytes are decoded for the check. A .ai or .ait name is still placed as the file says, and a path is still checked by its extension. A test covers unnamed bytes, another extension and a .ai name. --- crates/ui-egui/src/dialogs/import_pdf.rs | 21 ++++++++++++++++--- .../ui-egui/src/dialogs/tests_import_pdf.rs | 19 +++++++++++++++++ 2 files changed, 37 insertions(+), 3 deletions(-) diff --git a/crates/ui-egui/src/dialogs/import_pdf.rs b/crates/ui-egui/src/dialogs/import_pdf.rs index fe4603ccf0..5f97ea75ec 100644 --- a/crates/ui-egui/src/dialogs/import_pdf.rs +++ b/crates/ui-egui/src/dialogs/import_pdf.rs @@ -271,14 +271,14 @@ pub(crate) fn with_preferred_text_as(app: &VectorcraftApp, name: &str, bytes: &[ /// The `file.place` params `p` of a PDF placed embedded (Link off, from bytes or with a non-empty password), /// by the user or as a command, get the `pdfTextAs` preference as their `textAs` when it is Outlines and they have no -/// `textAs`. A linked page shows the file's own text, and a `.ai` or `.ait` file is placed as it -/// says. +/// `textAs`. Bytes are a PDF by their content ([`places_pdf`]). A linked page shows the file's own +/// text, and a `.ai` or `.ait` file is placed as it says. pub(crate) fn place_with_preferred_text_as(app: &VectorcraftApp, p: &mut Value) { let given = |k: &str| p.get(k).is_some_and(|v| !v.is_null()); let path = p.get("path").and_then(Value::as_str); let name = path.or_else(|| p.get("name").and_then(Value::as_str)).unwrap_or_default(); let linked = path.is_some() && p.get("link").and_then(Value::as_bool) != Some(false) && !password_given(p); - if given("textAs") || linked || preferred_text_as(app) == TextAs::Text || fileio::extension(name) != "pdf" { + if given("textAs") || linked || preferred_text_as(app) == TextAs::Text || !places_pdf(p, path, name) { return; } if let Some(o) = p.as_object_mut() { @@ -286,6 +286,21 @@ pub(crate) fn place_with_preferred_text_as(app: &VectorcraftApp, p: &mut Value) } } +/// Do the `file.place` params `p` place a PDF (not a `.ai` or `.ait` file, which is PDF inside): +/// a `path` by its extension, as [`place_source`] picks one, and `dataBase64` by its content, as +/// `file.place` reads it ([`fileio::detect`]: bytes that start with `%PDF`), so bytes without a +/// `name` or with another extension count too. Only the first bytes are decoded. +fn places_pdf(p: &Value, path: Option<&str>, name: &str) -> bool { + let ext = fileio::extension(name); + match (path, p.get("dataBase64").and_then(Value::as_str)) { + (None, Some(b64)) => { + let head: String = b64.chars().filter(|c| !c.is_ascii_whitespace()).take(8).collect(); + !matches!(ext.as_str(), "ai" | "ait") && vectorcraft_format::base64_decode(&head).is_some_and(|b| b.starts_with(b"%PDF")) + } + _ => ext == "pdf", + } +} + fn text_as(d: &Dialog) -> TextAs { text_as_of(&d.str("textAs")) } diff --git a/crates/ui-egui/src/dialogs/tests_import_pdf.rs b/crates/ui-egui/src/dialogs/tests_import_pdf.rs index 6e234bbd0c..5d60c04b36 100644 --- a/crates/ui-egui/src/dialogs/tests_import_pdf.rs +++ b/crates/ui-egui/src/dialogs/tests_import_pdf.rs @@ -532,6 +532,25 @@ fn file_place_without_the_dialog_takes_the_pdf_text_preference() { assert_eq!(type_objects(&app), 2, "Editable: page 1's type object"); } +/// PDF bytes placed without a `name`, or under another extension, are a PDF by their content, as +/// `file.place` reads them, and take the PDF Text preference; under a `.ai` name they are placed as +/// the file says. +#[test] +fn pdf_bytes_without_a_pdf_name_take_the_pdf_text_preference() { + let mut app = app(); + set_pdf_text(&mut app, "outlines"); + let data = vectorcraft_format::base64_encode(&text_pages(1)); + crate::place::run(&mut app, &json!({"dataBase64": data, "showImportOptions": false})).unwrap(); + assert!(app.ui.dialog.is_none(), "no dialog"); + assert_eq!(type_objects(&app), 0, "unnamed bytes: outlines"); + + crate::place::run(&mut app, &json!({"name": "page.bin", "dataBase64": data, "showImportOptions": false})).unwrap(); + assert_eq!(type_objects(&app), 0, "another extension: outlines"); + + crate::place::run(&mut app, &json!({"name": "page.ai", "dataBase64": data, "showImportOptions": false})).unwrap(); + assert_eq!(type_objects(&app), 1, "a .ai file: its own text"); +} + /// With Show Import Options off, an encrypted PDF placed with an empty `password` asks for its /// password, as one placed without a `password` does. #[test] From c85f3ebb5ac27d19d88ea164fad80844179a865f Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 22 Nov 2026 05:48:51 -0800 Subject: [PATCH 056/151] Scripts: keep a stopped startup script's report and refuse a chosen script that cannot start - A chosen script that script.run would refuse (a missing file, one larger than 8 MiB, bad parameters) ends script.startup.run with script.run's error before any startup script runs. - When a queued run ends, the next one starts at the following pump, so the ended run's report stays for the status bar. The queue counts as a running script, so other runs and edits stay refused in that gap, and Stop asked for in it stops the run that starts next. - Queued runs that could not start show in the status bar in the same frame, and the reply's failed list is not shown there again. --- crates/engine/src/cmd/scripts.rs | 43 ++++++++----- crates/engine/src/script/mod.rs | 33 +++++++--- crates/engine/src/session/execute.rs | 2 +- crates/engine/tests/script_startup.rs | 80 +++++++++++++++++++----- crates/ui-egui/src/script_runs.rs | 15 +++-- crates/ui-egui/src/tests/scripts_menu.rs | 65 +++++++++++++++++++ docs/mcp.md | 9 ++- 7 files changed, 202 insertions(+), 45 deletions(-) diff --git a/crates/engine/src/cmd/scripts.rs b/crates/engine/src/cmd/scripts.rs index ef0e4171c9..0484e170e0 100644 --- a/crates/engine/src/cmd/scripts.rs +++ b/crates/engine/src/cmd/scripts.rs @@ -158,6 +158,17 @@ const NOT_TEXT: &str = "the script is not UTF-8 text"; pub const TOO_LARGE: &str = "the script is too large to run"; fn run(s: &mut Session, p: &Value) -> Result { + let request = prepare(s, p)?; + let name = s.script_start(request)?; + if s.script_frames { + return Ok(json!({"running": true, "name": name})); + } + s.script_run_to_end() +} + +/// The run `script.run`'s parameters `p` ask for, with its file read and checked, or the error that +/// keeps it from starting. +fn prepare(s: &Session, p: &Value) -> Result { let optional_str = |key: &str| match p.get(key) { None => Ok(None), Some(Value::String(t)) => Ok(Some(t.as_str())), @@ -216,7 +227,7 @@ fn run(s: &mut Session, p: &Value) -> Result { }; let name = given_name.map(str::to_string).or_else(|| path.map(super::fileio::file_name)).unwrap_or_else(|| "script".to_string()); let locale = script::dollar::ui_locale(s.ui_language.as_deref().unwrap_or(&s.prefs.interface_language)); - let request = script::Request { + Ok(script::Request { name, name_given: given_name.is_some(), file: path.map(str::to_string), @@ -226,12 +237,7 @@ fn run(s: &mut Session, p: &Value) -> Result { fuel, locale, answers, - }; - let name = s.script_start(request)?; - if s.script_frames { - return Ok(json!({"running": true, "name": name})); - } - s.script_run_to_end() + }) } fn stop(s: &mut Session, _: &Value) -> Result { @@ -441,8 +447,12 @@ impl Session { /// [`Self::take_startup_failures`], and the next one starts. → the reply of the script queued /// after them when it ran to its end at once. pub(crate) fn start_queued(&mut self) -> Option { - while !self.script_running() { - match self.script_queue.pop_front()? { + // Held aside while a run starts, so that the queue does not count as a running script then. + let mut queue = std::mem::take(&mut self.script_queue); + let mut reply = None; + while self.script_key.is_none() { + let Some(next) = queue.pop_front() else { break }; + match next { script::startup::Queued::Startup { path, fuel } => { if let Err(e) = self.start_startup(&path, fuel) { self.startup_failures.push((file_name_of(&path), e)); @@ -450,15 +460,16 @@ impl Session { } script::startup::Queued::Then(params) => { match run(self, ¶ms) { - Ok(_) if self.script_running() => {} - Ok(v) => return Some(v), + Ok(_) if self.script_key.is_some() => {} + Ok(v) => reply = Some(v), Err(e) => self.startup_failures.push((then_name(¶ms), e.to_string())), } - return None; + break; } } } - None + self.script_queue = queue; + reply } /// The runs `script.startup.run` queued that could not start since the last call, as (name, @@ -517,6 +528,10 @@ fn startup_run(s: &mut Session, p: &Value) -> Result { if s.script_running() { return Err(EngineError::Busy); } + // A chosen script that cannot start ends the request before any startup script runs. + if let Some(then) = &then { + prepare(s, then)?; + } let root = match (s.startup_skip(), s.startup_scripts_dir()) { (None, Some(root)) => root.to_path_buf(), (why, _) => { @@ -541,7 +556,7 @@ fn startup_run(s: &mut Session, p: &Value) -> Result { let queued = s.script_queue.len(); s.startup_failures.clear(); let then = s.start_queued(); - let failed: Vec = s.startup_failures.iter().map(|(name, error)| json!({"name": name, "error": error})).collect(); + let failed: Vec = s.take_startup_failures().into_iter().map(|(name, error)| json!({"name": name, "error": error})).collect(); let mut out = json!({ "reason": reason, "skipped": false, diff --git a/crates/engine/src/script/mod.rs b/crates/engine/src/script/mod.rs index f5c1326c8d..d006f0500d 100644 --- a/crates/engine/src/script/mod.rs +++ b/crates/engine/src/script/mod.rs @@ -1653,9 +1653,10 @@ fn relocated(message: &str, old_line: u32, old_column: u32, line: u32, column: u } impl Session { - /// Is a script running? While one is, the commands that change anything are refused. + /// Is a script running, or a run `script.startup.run` queued waiting to start at the next + /// [`Self::script_pump`]? While one is, the commands that change anything are refused. pub fn script_running(&self) -> bool { - self.script_key.is_some() + self.script_key.is_some() || !self.script_queue.is_empty() } /// The named engine of the running script. @@ -1868,9 +1869,10 @@ impl Session { } } - /// Asks the running script to stop; it is rolled back at the next slice. False with none running. + /// Asks the running script to stop; it is rolled back at the next slice. Between two runs + /// `script.startup.run` queued, the next one stops as it starts. False with none running. pub fn script_request_stop(&mut self) -> bool { - if self.script_key.is_none() { + if !self.script_running() { return false; } self.script_stop.set(); @@ -2124,12 +2126,27 @@ impl Session { /// Advances the running script by one slice. `None` while it is still running; otherwise the /// run has ended: its report, or the error that ended it, with the documents put back. When - /// `script.startup.run` queued more runs, the next one starts then, and a queued run that cannot - /// start is kept for [`Self::take_startup_failures`]. + /// `script.startup.run` queued more runs, the next one starts at the pump after that, so the + /// ended run's report ([`Self::script_report`]) stays until then; a queued run that cannot start + /// is kept for [`Self::take_startup_failures`]. pub fn script_pump(&mut self) -> Option> { - let result = self.pump_one()?; + if self.script_key.is_none() { + // A stop asked for between two runs stops the run that starts now, which clears it. + let stop = self.script_stop.is_set(); + self.start_queued(); + if stop && self.script_key.is_some() { + self.script_stop.set(); + } else { + self.script_stop.clear(); + } + return None; + } + // Held aside while the run ends, so that its commit does not see the queue as a running script. + let queue = std::mem::take(&mut self.script_queue); + let result = self.pump_one(); + self.script_queue = queue; + let result = result?; self.startup_ended(); - self.start_queued(); Some(result) } diff --git a/crates/engine/src/session/execute.rs b/crates/engine/src/session/execute.rs index 046c480079..58a7c3848c 100644 --- a/crates/engine/src/session/execute.rs +++ b/crates/engine/src/session/execute.rs @@ -61,7 +61,7 @@ impl Session { pub fn execute(&mut self, id: &str, params: &Value) -> Result { let spec = find_command(id).ok_or_else(|| cmd::params::unknown_command(id))?; // A clipboard import is a query that replaces the clipboard, which the end of a run sets too. - if self.depth == 0 && self.script_key.is_some() && (waits_for_tool_edit(id) || id.starts_with("clipboard.import")) { + if self.depth == 0 && self.script_running() && (waits_for_tool_edit(id) || id.starts_with("clipboard.import")) { return Err(EngineError::Busy); } // A step of a batch a script runs is held to the same rule as the script's own commands. diff --git a/crates/engine/tests/script_startup.rs b/crates/engine/tests/script_startup.rs index 74afe9efa5..f0135636d4 100644 --- a/crates/engine/tests/script_startup.rs +++ b/crates/engine/tests/script_startup.rs @@ -266,27 +266,77 @@ fn in_the_app_the_runs_are_queued_and_the_launch_marker_names_the_running_startu } #[test] -fn in_the_app_a_chosen_script_that_cannot_start_leaves_the_startup_scripts_result() { +fn a_chosen_script_that_cannot_start_is_refused_before_any_startup_script_runs() { let _f = fresh(); let dir = tmp_dir("app-then"); write(&dir, "a.jsx", "vc.log(1);"); + let missing = dir.join("gone").join("missing.jsx"); + let then = json!({"path": missing.to_string_lossy()}); + for frames in [false, true] { + let mut s = session(&dir); + s.script_frames = frames; + let alone = s.execute("script.run", &then).unwrap_err().to_string(); + let e = s.execute("script.startup.run", &json!({"reason": "menu", "then": then})).unwrap_err(); + assert_eq!(e.to_string(), alone, "the error script.run gives, frames {frames}"); + assert!(!s.script_running()); + assert!(started(&s).is_empty(), "no startup script ran, frames {frames}"); + assert!(s.take_startup_failures().is_empty()); + let e = s.execute("script.startup.run", &json!({"reason": "menu", "then": {"name": "neither"}})).unwrap_err(); + assert!(e.to_string().contains("exactly one of"), "{e}"); + assert!(started(&s).is_empty()); + } +} + +#[test] +fn in_the_app_a_stopped_startup_script_keeps_its_report_until_the_next_pump_starts_the_queued_run() { + let _f = fresh(); + let dir = tmp_dir("app-stop"); + write(&dir, "a.jsx", "for (;;) {}"); let mut s = session(&dir); s.script_frames = true; - let missing = dir.join("gone").join("missing.jsx"); - let r = s.execute("script.startup.run", &json!({"reason": "menu", "then": {"path": missing.to_string_lossy()}})).unwrap(); - assert_eq!((r["running"].clone(), r["queued"].clone()), (json!(true), json!(2))); - let mut results = vec![]; - for _ in 0..10_000 { - if !s.script_running() { - break; - } - if let Some(r) = s.script_pump() { - results.push(r.is_ok()); + s.execute("script.startup.run", &json!({"reason": "menu", "then": {"source": "vc.log(2);", "name": "chosen"}})).unwrap(); + assert!(s.script_pump().is_none(), "the endless one runs"); + assert!(s.script_request_stop()); + let ended = (0..10_000).find_map(|_| s.script_pump()).unwrap(); + assert!(ended.is_err()); + assert_eq!(s.script_report().unwrap()["kind"], "stopped", "the ended run's report is still there"); + assert!(s.script_running(), "the chosen script waits for the next pump"); + // Nothing else starts ahead of the queued run. + let e = s.execute("script.run", &json!({"source": "vc.log(9);", "name": "direct"})).unwrap_err(); + assert!(matches!(e, vectorcraft_engine::EngineError::Busy), "{e}"); + assert_eq!(started(&s), ["a.jsx"]); + let r = (0..10_000).find_map(|_| s.script_pump()).unwrap(); + assert_eq!(r.unwrap()["ok"], true); + assert_eq!(started(&s), ["a.jsx", "chosen"]); + assert!(!s.script_running()); +} + +#[test] +fn in_the_app_a_stop_between_two_runs_stops_the_run_that_starts_next() { + let _f = fresh(); + let dir = tmp_dir("app-stop-between"); + write(&dir, "a.jsx", "vc.log(1);"); + write(&dir, "b.jsx", "for (;;) {}"); + for by_interrupt in [false, true] { + let mut s = session(&dir); + s.script_frames = true; + let then = json!({"source": "vc.log(3);", "name": "chosen"}); + s.execute("script.startup.run", &json!({"reason": "menu", "then": then, "maxFuel": 1_000_000})).unwrap(); + assert_eq!((0..10_000).find_map(|_| s.script_pump()).unwrap().unwrap()["ok"], true, "a.jsx ends"); + assert!(s.script_running(), "b.jsx waits for the next pump"); + if by_interrupt { + // The status bar's Stop button. + s.script_interrupt().set(); + } else { + assert!(s.script_request_stop(), "script.stop has a run to stop"); } + let ended = (0..10_000).find_map(|_| s.script_pump()).unwrap(); + assert!(ended.is_err()); + assert_eq!(s.script_report().unwrap()["kind"], "stopped"); + assert_eq!(s.script_report().unwrap()["name"], "b.jsx"); + assert_eq!((0..10_000).find_map(|_| s.script_pump()).unwrap().unwrap()["ok"], true, "the chosen script still runs"); + assert_eq!(started(&s), ["a.jsx", "b.jsx", "chosen"]); } - assert_eq!(results, [true], "the startup script's own result"); - let failures = s.take_startup_failures(); - assert_eq!(failures.iter().map(|(name, _)| name.as_str()).collect::>(), ["missing.jsx"]); } #[test] @@ -301,5 +351,5 @@ fn in_the_app_startup_scripts_that_cannot_start_are_in_the_reply() { let r = s.execute("script.startup.run", &json!({"reason": "launch"})).unwrap(); assert_eq!(r["running"], json!(false)); assert_eq!(r["failed"], json!([{"name": "big.jsx", "error": vectorcraft_engine::cmd::scripts::TOO_LARGE}])); - assert_eq!(s.take_startup_failures().len(), 1, "and kept for the app's status bar"); + assert!(s.take_startup_failures().is_empty(), "the reply names them, so the status bar does not again"); } diff --git a/crates/ui-egui/src/script_runs.rs b/crates/ui-egui/src/script_runs.rs index 907bbdb9bc..41f25e3f72 100644 --- a/crates/ui-egui/src/script_runs.rs +++ b/crates/ui-egui/src/script_runs.rs @@ -12,10 +12,7 @@ use crate::state::Dialog; /// Advances the running script by one slice, or asks what its growth needs asked. pub fn poll(app: &mut VectorcraftApp) { script_run::drain(app); - // Each run `script.startup.run` queued that could not start. - for (name, error) in app.session.take_startup_failures() { - app.status(format!("{name}: {error}")); - } + startup_failures(app); if !app.session.script_running() { return; } @@ -26,6 +23,9 @@ pub fn poll(app: &mut VectorcraftApp) { let name = app.session.script_name().unwrap_or_default(); let cursor_settings = (app.session.caps_lock, app.session.prefs.use_precise_cursors); let Some(result) = app.session.script_pump() else { + // A pump that started the next queued run shows the runs before it that could not start + // in this frame: with none left running, the app may draw no next one. + startup_failures(app); // The app draws no more frames while the run waits: its question opens in this one. ask(app); return; @@ -49,6 +49,13 @@ pub fn poll(app: &mut VectorcraftApp) { app.sync_views(); } +/// Shows each run `script.startup.run` queued that could not start. +fn startup_failures(app: &mut VectorcraftApp) { + for (name, error) in app.session.take_startup_failures() { + app.status(format!("{name}: {error}")); + } +} + /// Opens what the run waits at, once no other dialog is open: the script's own dialog, or the /// question about its growth. Closes the script's dialog when the run no longer waits at it. /// → true while the run waits. diff --git a/crates/ui-egui/src/tests/scripts_menu.rs b/crates/ui-egui/src/tests/scripts_menu.rs index c1f418e62b..405593d3d6 100644 --- a/crates/ui-egui/src/tests/scripts_menu.rs +++ b/crates/ui-egui/src/tests/scripts_menu.rs @@ -600,6 +600,71 @@ fn with_run_startup_scripts_on_other_script_and_the_launch_run_the_startup_scrip let _ = std::fs::remove_dir_all(dir); } +#[test] +fn a_stopped_startup_script_says_it_was_stopped_and_the_chosen_script_still_runs() { + let dir = folder("startup-stop"); + let mut app = app(&dir); + let startup = dir.join("Startup Scripts"); + std::fs::create_dir_all(&startup).unwrap(); + std::fs::write(startup.join("a.jsx"), "for (;;) {}").unwrap(); + app.session.attach_startup_scripts_dir(startup); + app.session.prefs.show_external_script_warning = false; + app.run("prefs.set", json!({"key": "runStartupScripts", "value": true})).unwrap(); + menus::run_ui_command(&mut app, "ui.runScript", &json!({ "source": DRAW, "name": "chosen" })).unwrap().unwrap(); + script_runs::poll(&mut app); + assert!(app.session.script_request_stop()); + app.status("before"); + for _ in 0..10_000 { + if app.ui.status != "before" { + break; + } + script_runs::poll(&mut app); + } + assert_eq!(app.ui.status, "The script was stopped and its changes were undone"); + finish(&mut app); + assert_eq!(started(&app), ["a.jsx", "chosen"]); + assert_eq!(app.ui.status, "Ran chosen"); + let _ = std::fs::remove_dir_all(dir); +} + +#[test] +fn a_last_startup_script_that_cannot_start_shows_in_the_status_bar_when_the_runs_end() { + let dir = folder("startup-last-fails"); + let mut app = app(&dir); + startup_folder(&mut app, &dir); + let mut big = "//".to_string(); + big.push_str(&"x".repeat(vectorcraft_engine::script::MAX_SOURCE_BYTES)); + std::fs::write(dir.join("Startup Scripts").join("b.jsx"), big).unwrap(); + app.run("prefs.set", json!({"key": "runStartupScripts", "value": true})).unwrap(); + script_runs::run_at_launch(&mut app); + finish(&mut app); + assert_eq!(started(&app), ["a.jsx", "b.jsx"]); + assert_eq!(app.ui.status, format!("b.jsx: {}", vectorcraft_engine::cmd::scripts::TOO_LARGE)); + let _ = std::fs::remove_dir_all(dir); +} + +#[test] +fn with_run_startup_scripts_on_other_script_with_a_missing_file_fails_before_the_startup_scripts() { + let dir = folder("startup-missing"); + let mut app = app(&dir); + startup_folder(&mut app, &dir); + app.run("prefs.set", json!({"key": "runStartupScripts", "value": true})).unwrap(); + let missing = dir.join("gone.jsx").to_string_lossy().into_owned(); + let alone = app.run("script.run", json!({ "path": missing })).unwrap_err(); + for warning in [false, true] { + app.session.prefs.show_external_script_warning = warning; + let e = match menus::run_ui_command(&mut app, "ui.runScript", &json!({ "path": missing })).unwrap() { + Err(e) => e, + // The warning opens first; its Run button gives the error. + Ok(_) => crate::dialogs::confirm(&mut app).unwrap_err(), + }; + assert_eq!(e, alone, "the error script.run gives, warning {warning}"); + assert!(!app.session.script_running()); + assert!(started(&app).is_empty(), "no startup script ran, warning {warning}"); + } + let _ = std::fs::remove_dir_all(dir); +} + #[test] fn a_startup_scripts_folder_that_cannot_be_read_shows_in_the_status_bar_at_launch_and_a_missing_one_does_not() { let dir = folder("startup-unreadable"); diff --git a/docs/mcp.md b/docs/mcp.md index 6f81dbb3f7..761ad4a579 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -3191,13 +3191,16 @@ The rest of this section is VectorCraft's own rules: `vectorcraft-cli` uses the same folder and runs it only through `script.startup.run`. `script.startup.run {reason: launch|menu, then?, maxFuel?}` runs the folder now. `then` holds `script.run`'s -parameters for a script that runs after the startup scripts; `maxFuel` limits each startup script's instructions +parameters for a script that runs after the startup scripts. A `then` that `script.run` would refuse, such as a +missing file or one larger than 8 MiB, ends the request with `script.run`'s error before any startup script runs. +`maxFuel` limits each startup script's instructions (from 1 to 100,000,000,000, default 1,000,000,000). It returns `{reason, skipped: true, why}` with `why` set to `off`, `safeMode` or `noFolder` when nothing runs, and otherwise `{reason, skipped: false, ran, failed: [{name, error}], disabled, truncated, unreadable}`, with `then` holding `script.run`'s reply. In the app the runs are queued and the reply is `{reason, skipped: false, running, queued, failed, disabled, truncated, unreadable}`, with `failed` naming -the runs that could not start before the first one did; each run then reports as a `script.run` in the app does, and -a later run that cannot start, the chosen script included, is named in the status bar. Under `--automation-read-root` it reads the folder only when the folder lies inside a +the runs that could not start before the first one did. Each run then reports as a `script.run` in the app does, the +next one starts at the frame after, and a later run that cannot start, the chosen script included, is named in the +status bar. Stop (`script.stop`) asked for between two runs stops the run that starts next. Under `--automation-read-root` it reads the folder only when the folder lies inside a read root. ```sh From b7f2eacc6aad0196a8dcd4ffbce0dd490f62da40 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 22 Nov 2026 05:58:13 -0800 Subject: [PATCH 057/151] Canvas: a click pressed and released in one frame ends with its release's modifiers A press whose release came in the same frame started the gesture and left the release for the next frame, which read that frame's modifiers, Space and position. Alt pressed before the release and let go after it in the frame then opened the Rectangle dialog without centering the shape on the click. The press now ends the gesture in its own frame, through the same release path a held drag takes, with the modifiers, Space and position of the button-up. --- crates/ui-egui/src/canvas/input.rs | 24 ++++++++++++++++------ crates/ui-egui/src/canvas/tests.rs | 33 ++++++++++++++++++++++++++++++ 2 files changed, 51 insertions(+), 6 deletions(-) diff --git a/crates/ui-egui/src/canvas/input.rs b/crates/ui-egui/src/canvas/input.rs index 5be38cd994..b996462561 100644 --- a/crates/ui-egui/src/canvas/input.rs +++ b/crates/ui-egui/src/canvas/input.rs @@ -121,6 +121,13 @@ pub(super) fn handle_input(app: &mut VectorcraftApp, ui: &Ui, resp: &egui::Respo ui.data_mut(|dd| dd.insert_temp(name_press_id(), (i, press_shift))); } else { begin_drag(app, ui, &f, p); + // Pressed and released in this frame (a quick click or tap): the press ends now, with + // the modifiers, Space and position of its release, not those of the next frame. + if !pointer.primary_down() + && let Some(d) = ui.data(|dd| dd.get_temp::(drag_id())) + { + end_drag(app, ui, &f, d, egui::PointerButton::Primary, p); + } } } else if drag.is_none() && resp.hovered() @@ -140,12 +147,7 @@ pub(super) fn handle_input(app: &mut VectorcraftApp, ui: &Ui, resp: &egui::Respo if held { drag_held(app, ui, &f, d, p); } else { - // The drag ends where its button went up, with the modifiers and Space held then: the - // moves and key changes after the release in this frame do not count. - let m = release_mods(ui, button).unwrap_or(f.m); - let space = space_lends_view_tools(app, m, key_at_release(ui, egui::Key::Space, button, f.space_before)); - let up = Pointing { m, space, ..f }; - drag_released(app, ui, &up, d, release_pos(ui, button, false).unwrap_or(p)); + end_drag(app, ui, &f, d, button, p); } } else if let Some(p) = hover_tool // A press on an artboard's name starts no drag: the moves while it is held are not hover. @@ -594,6 +596,16 @@ fn dispatch_frame_moves(app: &mut VectorcraftApp, ui: &Ui, f: &Pointing, backquo } } +/// A gesture whose `button` went up ends where it went up, with the modifiers and Space held then: +/// the moves and key changes after the release in this frame do not count. Without a release in +/// this frame, it ends at `p` with the modifiers and Space held now. +fn end_drag(app: &mut VectorcraftApp, ui: &Ui, f: &Pointing, d: Drag, button: egui::PointerButton, p: Pos2) { + let m = release_mods(ui, button).unwrap_or(f.m); + let space = space_lends_view_tools(app, m, key_at_release(ui, egui::Key::Space, button, f.space_before)); + let up = Pointing { m, space, ..*f }; + drag_released(app, ui, &up, d, release_pos(ui, button, false).unwrap_or(p)); +} + /// A gesture released at `p`: the view settles, or the tool gets its up. fn drag_released(app: &mut VectorcraftApp, ui: &Ui, f: &Pointing, d: Drag, p: Pos2) { let Pointing { resp, rect, m, space, xf, view, .. } = *f; diff --git a/crates/ui-egui/src/canvas/tests.rs b/crates/ui-egui/src/canvas/tests.rs index 73b2d37547..a72dd436ff 100644 --- a/crates/ui-egui/src/canvas/tests.rs +++ b/crates/ui-egui/src/canvas/tests.rs @@ -1476,6 +1476,39 @@ fn shift_pressed_at_a_still_release_constrains_the_tool_drag() { assert!((w - h).abs() < 1e-6, "Shift pressed at a still release draws a square, got {w} x {h}"); } +/// A click whose press and release come in one frame ends with the modifiers held at its release, +/// not those of the next frame: Alt pressed before the release and let go after it in that frame +/// opens the Rectangle dialog centered on the click, and Alt pressed after the release does not. +#[test] +fn a_click_within_one_frame_ends_with_the_modifiers_of_its_release() { + let click = |held: egui::Modifiers, after: egui::Modifiers| { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.session.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + app.select_tool("rectangle"); + let ctx = egui::Context::default(); + frame(&mut app, &ctx, vec![]); + let at = app.canvas_rect.unwrap().center(); + let b = |pressed, modifiers| egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers }; + frame( + &mut app, + &ctx, + vec![ + egui::Event::PointerMoved(at), + b(true, egui::Modifiers::NONE), + egui::Event::ModifiersChanged(held), + b(false, held), + egui::Event::ModifiersChanged(after), + ], + ); + frame(&mut app, &ctx, vec![egui::Event::ModifiersChanged(egui::Modifiers::NONE)]); + let d = app.ui.dialog.as_ref().expect("the click opens the Rectangle dialog"); + assert_eq!(d.kind, "rectangle"); + d.fields.get("alt").cloned() + }; + assert_eq!(click(egui::Modifiers::ALT, egui::Modifiers::NONE), Some(json!(true)), "Alt held at the release centers the rectangle"); + assert_eq!(click(egui::Modifiers::NONE, egui::Modifiers::ALT), Some(json!(false)), "Alt pressed after the release does not"); +} + /// Space pressed after a tool drag's release, in the same frame, does not count for the drag: the /// Rectangle tool's last move still resizes the rectangle instead of moving it. #[test] From 3a00d4a73a83740940e2fccf55d46587a110a688 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 22 Nov 2026 06:15:57 -0800 Subject: [PATCH 058/151] Scripts: show startup scripts that cannot start when a launch or chosen run begins script.startup.run returns the startup scripts that could not start before the first run did, such as a file larger than 8 MiB, in its reply's failed list. The launch and the File > Scripts runs now show each one in the status bar as name: error, so a launch where every startup script fails to start no longer shows nothing. --- crates/ui-egui/src/script_runs.rs | 24 ++++++++++--- crates/ui-egui/src/tests/scripts_menu.rs | 44 ++++++++++++++++++++++++ 2 files changed, 64 insertions(+), 4 deletions(-) diff --git a/crates/ui-egui/src/script_runs.rs b/crates/ui-egui/src/script_runs.rs index 41f25e3f72..034daa9672 100644 --- a/crates/ui-egui/src/script_runs.rs +++ b/crates/ui-egui/src/script_runs.rs @@ -89,12 +89,24 @@ fn ask(app: &mut VectorcraftApp) -> bool { } /// Runs the script of `params` (`script.run`'s) that the person chose from File › Scripts, after -/// the startup scripts when General › Run Startup Scripts is on (`script.startup.run`). +/// the startup scripts when General › Run Startup Scripts is on (`script.startup.run`). A startup +/// script that cannot start shows in the status bar. pub(crate) fn run_chosen(app: &mut VectorcraftApp, params: Value) -> Result { if app.session.startup_skip().is_some() { return app.run("script.run", params); } - app.run("script.startup.run", json!({"reason": "menu", "then": params})) + let reply = app.run("script.startup.run", json!({"reason": "menu", "then": params}))?; + reply_failures(app, &reply); + Ok(reply) +} + +/// Shows each startup script that a `script.startup.run` reply names under `failed`: the queued +/// runs that could not start before the first one did. +fn reply_failures(app: &mut VectorcraftApp, reply: &Value) { + for failed in reply["failed"].as_array().into_iter().flatten() { + let (name, error) = (failed["name"].as_str().unwrap_or_default(), failed["error"].as_str().unwrap_or_default()); + app.status(format!("{name}: {error}")); + } } /// When the app has started, out of Safe Mode: the startup scripts run when General › Run Startup @@ -105,8 +117,12 @@ pub fn run_at_launch(app: &mut VectorcraftApp) { return; } match app.run("script.startup.run", json!({"reason": "launch"})) { - Ok(reply) if reply["unreadable"] == true => app.status("The Startup Scripts folder cannot be read"), - Ok(_) => {} + Ok(reply) => { + reply_failures(app, &reply); + if reply["unreadable"] == true { + app.status("The Startup Scripts folder cannot be read"); + } + } Err(e) => app.status(e), } } diff --git a/crates/ui-egui/src/tests/scripts_menu.rs b/crates/ui-egui/src/tests/scripts_menu.rs index 405593d3d6..e6cc2896cd 100644 --- a/crates/ui-egui/src/tests/scripts_menu.rs +++ b/crates/ui-egui/src/tests/scripts_menu.rs @@ -643,6 +643,50 @@ fn a_last_startup_script_that_cannot_start_shows_in_the_status_bar_when_the_runs let _ = std::fs::remove_dir_all(dir); } +/// `dir`'s `Startup Scripts` folder, attached to `app`, holding only `0.jsx`, too large to run. +fn oversized_startup_folder(app: &mut VectorcraftApp, dir: &std::path::Path) { + let startup = dir.join("Startup Scripts"); + std::fs::create_dir_all(&startup).unwrap(); + let mut big = "//".to_string(); + big.push_str(&"x".repeat(vectorcraft_engine::script::MAX_SOURCE_BYTES)); + std::fs::write(startup.join("0.jsx"), big).unwrap(); + app.session.attach_startup_scripts_dir(startup); +} + +#[test] +fn a_launch_whose_only_startup_script_cannot_start_shows_it_in_the_status_bar() { + let dir = folder("startup-launch-too-large"); + let mut app = app(&dir); + oversized_startup_folder(&mut app, &dir); + app.run("prefs.set", json!({"key": "runStartupScripts", "value": true})).unwrap(); + app.status("before"); + script_runs::run_at_launch(&mut app); + let shown = format!("0.jsx: {}", vectorcraft_engine::cmd::scripts::TOO_LARGE); + assert_eq!(app.ui.status, shown); + assert!(!app.session.script_running()); + script_runs::poll(&mut app); + assert_eq!(app.ui.status, shown); + assert_eq!(objects(&app), 0); + let _ = std::fs::remove_dir_all(dir); +} + +#[test] +fn a_menu_run_after_a_first_startup_script_that_cannot_start_shows_it_and_runs_the_chosen_script() { + let dir = folder("startup-menu-too-large"); + let mut app = app(&dir); + oversized_startup_folder(&mut app, &dir); + app.session.prefs.show_external_script_warning = false; + app.run("prefs.set", json!({"key": "runStartupScripts", "value": true})).unwrap(); + app.status("before"); + menus::run_ui_command(&mut app, "ui.runScript", &json!({ "source": DRAW, "name": "chosen" })).unwrap().unwrap(); + assert_eq!(app.ui.status, format!("0.jsx: {}", vectorcraft_engine::cmd::scripts::TOO_LARGE)); + finish(&mut app); + assert_eq!(started(&app), ["0.jsx", "chosen"]); + assert_eq!(objects(&app), 2); + assert_eq!(app.ui.status, "Ran chosen"); + let _ = std::fs::remove_dir_all(dir); +} + #[test] fn with_run_startup_scripts_on_other_script_with_a_missing_file_fails_before_the_startup_scripts() { let dir = folder("startup-missing"); From e1b15ecea6193262a7ba4ddd4a7f0eee4f86a287 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 22 Nov 2026 06:59:03 -0800 Subject: [PATCH 059/151] Canvas: a click pressed and released in one frame starts where it was pressed A press and release that come in one frame now start the gesture at the press's own position, not where the pointer moved after the release in that frame. With Animated Zoom off, such a Zoom tool click whose pointer then moves away steps the zoom instead of zooming to the area between the release and the new hover position, and a drag pressed, moved and released in one frame zooms to the area dragged across. The Hand, Rotate View and tool presses start at the press position the same way. --- crates/ui-egui/src/canvas/input.rs | 23 +++++++++++++----- crates/ui-egui/src/canvas/tests.rs | 38 ++++++++++++++++++++++++++++++ 2 files changed, 55 insertions(+), 6 deletions(-) diff --git a/crates/ui-egui/src/canvas/input.rs b/crates/ui-egui/src/canvas/input.rs index b996462561..a4ca1863c0 100644 --- a/crates/ui-egui/src/canvas/input.rs +++ b/crates/ui-egui/src/canvas/input.rs @@ -120,13 +120,14 @@ pub(super) fn handle_input(app: &mut VectorcraftApp, ui: &Ui, resp: &egui::Respo .unwrap_or(m.shift); ui.data_mut(|dd| dd.insert_temp(name_press_id(), (i, press_shift))); } else { - begin_drag(app, ui, &f, p); - // Pressed and released in this frame (a quick click or tap): the press ends now, with + // Pressed and released in this frame (a quick click or tap): the press starts where the + // button went down, not where the pointer moved to after the release, and ends now, with // the modifiers, Space and position of its release, not those of the next frame. - if !pointer.primary_down() - && let Some(d) = ui.data(|dd| dd.get_temp::(drag_id())) - { - end_drag(app, ui, &f, d, egui::PointerButton::Primary, p); + let released = !pointer.primary_down(); + let start = if released { press_pos(ui, egui::PointerButton::Primary).filter(|q| rect.contains(*q)).unwrap_or(p) } else { p }; + begin_drag(app, ui, &f, start); + if released && let Some(d) = ui.data(|dd| dd.get_temp::(drag_id())) { + end_drag(app, ui, &f, d, egui::PointerButton::Primary, start); } } } else if drag.is_none() @@ -768,6 +769,16 @@ fn release_pos(ui: &Ui, button: egui::PointerButton, last: bool) -> Option }) } +/// Where `button` first went down in this frame. +fn press_pos(ui: &Ui, button: egui::PointerButton) -> Option { + ui.input(|i| { + i.events.iter().find_map(|e| match e { + egui::Event::PointerButton { pos, button: b, pressed: true, .. } if *b == button => Some(*pos), + _ => None, + }) + }) +} + /// The modifiers held when `button` first went up in this frame, the release that ends a drag. fn release_mods(ui: &Ui, button: egui::PointerButton) -> Option { ui.input(|i| { diff --git a/crates/ui-egui/src/canvas/tests.rs b/crates/ui-egui/src/canvas/tests.rs index a72dd436ff..e1a4260f03 100644 --- a/crates/ui-egui/src/canvas/tests.rs +++ b/crates/ui-egui/src/canvas/tests.rs @@ -1509,6 +1509,44 @@ fn a_click_within_one_frame_ends_with_the_modifiers_of_its_release() { assert_eq!(click(egui::Modifiers::NONE, egui::Modifiers::ALT), Some(json!(false)), "Alt pressed after the release does not"); } +/// With Animated Zoom off, a Zoom tool click whose press and release come in one frame steps the +/// zoom though the pointer then moves away in that frame, and a drag from the press to the release +/// zooms to the area dragged across, in one frame or over several. +#[test] +fn a_zoom_click_within_one_frame_starts_where_it_was_pressed() { + use egui::Event; + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.session.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + app.run("prefs.set", json!({"key": "animatedZoom", "value": false})).unwrap(); + app.select_tool("zoom"); + let ctx = egui::Context::default(); + frame(&mut app, &ctx, vec![]); + let rect = app.canvas_rect.unwrap(); + let at = rect.center() - vec2(100.0, 50.0); + let to = at + vec2(100.0, 50.0); + let button = |pos, pressed| Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() }; + let area = |z0: f64| z0 * f64::from((rect.width() / 100.0).min(rect.height() / 50.0)); + let z0 = app.view().unwrap().zoom; + frame(&mut app, &ctx, vec![Event::PointerMoved(at)]); + frame(&mut app, &ctx, vec![button(at, true), button(at, false), Event::PointerMoved(to)]); + frame(&mut app, &ctx, vec![]); + assert_eq!(app.view().unwrap().zoom, crate::state::next_zoom(z0, true), "a click steps the zoom"); + for one_frame in [true, false] { + app.view_mut().unwrap().zoom = z0; + frame(&mut app, &ctx, vec![Event::PointerMoved(at)]); + if one_frame { + frame(&mut app, &ctx, vec![button(at, true), Event::PointerMoved(to), button(to, false)]); + } else { + frame(&mut app, &ctx, vec![button(at, true)]); + frame(&mut app, &ctx, vec![Event::PointerMoved(to)]); + frame(&mut app, &ctx, vec![button(to, false)]); + } + frame(&mut app, &ctx, vec![]); + let z = app.view().unwrap().zoom; + assert!((z - area(z0)).abs() < 1e-6, "a drag (one frame: {one_frame}) zooms to its area: {z0} → {z}, not {}", area(z0)); + } +} + /// Space pressed after a tool drag's release, in the same frame, does not count for the drag: the /// Rectangle tool's last move still resizes the rectangle instead of moving it. #[test] From 81dfbf4078312c3ebb02d7923f2d9a3ac26defe8 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 22 Nov 2026 07:28:58 -0800 Subject: [PATCH 060/151] Scripts: keep startup notes in the status bar when a folder is not read in full A startup round whose listing of the Startup Scripts folder stopped at a limit or skipped an entry now says that the folder was not read in full, at launch and before a script chosen from File > Scripts. A folder that cannot be read is named before a chosen script too, not only at launch. The notes of a round (startup scripts that could not start and the two folder notes) no longer replace each other: the status bar shows the first and its hover lists them all. When the round's last run ends they show again, with that run's message in the hover, so a later message does not hide them. --- crates/ui-egui/src/i18n/bg.tsv | 1 + crates/ui-egui/src/i18n/bs.tsv | 1 + crates/ui-egui/src/i18n/ca.tsv | 1 + crates/ui-egui/src/i18n/cs.tsv | 1 + crates/ui-egui/src/i18n/da.tsv | 1 + crates/ui-egui/src/i18n/de.tsv | 1 + crates/ui-egui/src/i18n/el.tsv | 1 + crates/ui-egui/src/i18n/es.tsv | 1 + crates/ui-egui/src/i18n/fi.tsv | 1 + crates/ui-egui/src/i18n/fr.tsv | 1 + crates/ui-egui/src/i18n/gu.tsv | 1 + crates/ui-egui/src/i18n/hi.tsv | 1 + crates/ui-egui/src/i18n/hu.tsv | 1 + crates/ui-egui/src/i18n/id.tsv | 1 + crates/ui-egui/src/i18n/it.tsv | 1 + crates/ui-egui/src/i18n/ja.tsv | 1 + crates/ui-egui/src/i18n/ka.tsv | 1 + crates/ui-egui/src/i18n/ko.tsv | 1 + crates/ui-egui/src/i18n/nl.tsv | 1 + crates/ui-egui/src/i18n/pl.tsv | 1 + crates/ui-egui/src/i18n/pt-br.tsv | 1 + crates/ui-egui/src/i18n/ru.tsv | 1 + crates/ui-egui/src/i18n/sv.tsv | 1 + crates/ui-egui/src/i18n/tests.rs | 13 ++++ crates/ui-egui/src/i18n/tr.tsv | 1 + crates/ui-egui/src/i18n/uk.tsv | 1 + crates/ui-egui/src/i18n/vi.tsv | 1 + crates/ui-egui/src/i18n/zh-hans.tsv | 1 + crates/ui-egui/src/i18n/zh-hant.tsv | 1 + crates/ui-egui/src/script_runs.rs | 97 +++++++++++++++++++----- crates/ui-egui/src/state.rs | 6 ++ crates/ui-egui/src/tests/scripts_menu.rs | 82 +++++++++++++++++++- docs/mcp.md | 8 +- 33 files changed, 211 insertions(+), 23 deletions(-) diff --git a/crates/ui-egui/src/i18n/bg.tsv b/crates/ui-egui/src/i18n/bg.tsv index 038f2d5202..d7c3a7edb0 100644 --- a/crates/ui-egui/src/i18n/bg.tsv +++ b/crates/ui-egui/src/i18n/bg.tsv @@ -2617,6 +2617,7 @@ font-technology Variable Променливи Some scripts were not listed Някои скриптове не са изброени The Scripts folder cannot be read Папката Scripts не може да бъде прочетена @msg The Startup Scripts folder cannot be read Папката Startup Scripts не може да бъде прочетена +@msg The Startup Scripts folder was not read in full Папката Startup Scripts не беше прочетена изцяло Loading scripts… Зареждане на скриптовете… The Scripts folder is still being read Папката Scripts все още се чете Other Script… Друг скрипт… diff --git a/crates/ui-egui/src/i18n/bs.tsv b/crates/ui-egui/src/i18n/bs.tsv index 1a58a61708..2026ddb5c6 100644 --- a/crates/ui-egui/src/i18n/bs.tsv +++ b/crates/ui-egui/src/i18n/bs.tsv @@ -65,6 +65,7 @@ Some scripts were not listed Neke skripte nisu navedene The Scripts folder cannot be read Folder Scripts se ne može pročitati @msg The Startup Scripts folder cannot be read Folder Startup Scripts se ne može pročitati +@msg The Startup Scripts folder was not read in full Folder Startup Scripts nije pročitan u potpunosti Loading scripts… Učitavanje skripti… The Scripts folder is still being read Folder Scripts se još čita Other Script… Druga skripta… diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index 3c32c8ba57..57626d1dbe 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -6442,6 +6442,7 @@ digits Malayalam Malaiàlam Some scripts were not listed Alguns scripts no s'han llistat The Scripts folder cannot be read No es pot llegir la carpeta Scripts @msg The Startup Scripts folder cannot be read No es pot llegir la carpeta Startup Scripts +@msg The Startup Scripts folder was not read in full La carpeta Startup Scripts no s'ha llegit sencera Loading scripts… S’estan carregant els scripts… The Scripts folder is still being read Encara s’està llegint la carpeta Scripts @msg the script's run is no longer available l'execució de l'script ja no està disponible diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index 4ed3478543..e28cdc9b06 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -5250,6 +5250,7 @@ imageTrace Outline Obrys Some scripts were not listed Některé skripty nebyly uvedeny The Scripts folder cannot be read Složku Scripts nelze přečíst @msg The Startup Scripts folder cannot be read Složku Startup Scripts nelze přečíst +@msg The Startup Scripts folder was not read in full Složka Startup Scripts nebyla přečtena celá Loading scripts… Načítání skriptů… The Scripts folder is still being read Složka Scripts se stále načítá @msg the script's run is no longer available běh skriptu již není k dispozici diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index 6349480e27..f8770ce06d 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -821,6 +821,7 @@ liquify-list-end {0}, {1} {0} og {1} Some scripts were not listed Nogle scripter blev ikke vist The Scripts folder cannot be read Mappen Scripts kan ikke læses @msg The Startup Scripts folder cannot be read Mappen Startup Scripts kan ikke læses +@msg The Startup Scripts folder was not read in full Mappen Startup Scripts blev ikke læst helt Loading scripts… Indlæser scripter… The Scripts folder is still being read Mappen Scripts læses stadig Other Script… Andet script… diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index 0b51de1ba1..2b505e7c8a 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -4835,6 +4835,7 @@ theme Appearance Erscheinungsbild Some scripts were not listed Einige Skripte wurden nicht aufgeführt The Scripts folder cannot be read Der Ordner „Scripts“ kann nicht gelesen werden @msg The Startup Scripts folder cannot be read Der Ordner „Startup Scripts“ kann nicht gelesen werden +@msg The Startup Scripts folder was not read in full Der Ordner „Startup Scripts“ wurde nicht vollständig gelesen Loading scripts… Skripte werden geladen… The Scripts folder is still being read Der Ordner „Scripts“ wird noch gelesen @msg the script's run is no longer available der Lauf des Skripts ist nicht mehr verfügbar diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index 53de3bac32..cf36e0c008 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -2638,6 +2638,7 @@ axis Both Και τα δύο Some scripts were not listed Ορισμένα σενάρια δεν εμφανίζονται στη λίστα The Scripts folder cannot be read Δεν είναι δυνατή η ανάγνωση του φακέλου Scripts @msg The Startup Scripts folder cannot be read Δεν είναι δυνατή η ανάγνωση του φακέλου Startup Scripts +@msg The Startup Scripts folder was not read in full Ο φάκελος Startup Scripts δεν διαβάστηκε πλήρως Loading scripts… Φόρτωση σεναρίων… The Scripts folder is still being read Ο φάκελος Scripts διαβάζεται ακόμα @msg the script's run is no longer available η εκτέλεση του σεναρίου δεν είναι πλέον διαθέσιμη diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index 13c451f657..5ef68b3790 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -4914,6 +4914,7 @@ axis Both Ambos Some scripts were not listed Algunos scripts no se han incluido en la lista The Scripts folder cannot be read No se puede leer la carpeta Scripts @msg The Startup Scripts folder cannot be read No se puede leer la carpeta Startup Scripts +@msg The Startup Scripts folder was not read in full La carpeta Startup Scripts no se leyó por completo Loading scripts… Cargando scripts… The Scripts folder is still being read Aún se está leyendo la carpeta Scripts @msg the script's run is no longer available la ejecución del script ya no está disponible diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index 9f9a2a66ee..2d2df9edd1 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -5155,6 +5155,7 @@ imageTrace Outline Ääriviiva Some scripts were not listed Kaikkia komentosarjoja ei ole lueteltu The Scripts folder cannot be read Scripts-kansiota ei voi lukea @msg The Startup Scripts folder cannot be read Startup Scripts -kansiota ei voi lukea +@msg The Startup Scripts folder was not read in full Startup Scripts -kansiota ei luettu kokonaan Loading scripts… Ladataan komentosarjoja… The Scripts folder is still being read Scripts-kansiota luetaan vielä @msg the script's run is no longer available komentosarjan suoritus ei ole enää käytettävissä diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index bec8831a3a..3a89f2a5c1 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -4896,6 +4896,7 @@ axis Both Les deux Some scripts were not listed Certains scripts ne sont pas répertoriés The Scripts folder cannot be read Impossible de lire le dossier Scripts @msg The Startup Scripts folder cannot be read Impossible de lire le dossier Startup Scripts +@msg The Startup Scripts folder was not read in full Le dossier Startup Scripts n’a pas été lu en entier Loading scripts… Chargement des scripts… The Scripts folder is still being read Le dossier Scripts est encore en cours de lecture @msg the script's run is no longer available l’exécution du script n’est plus disponible diff --git a/crates/ui-egui/src/i18n/gu.tsv b/crates/ui-egui/src/i18n/gu.tsv index f735c1fd95..086a7c1388 100644 --- a/crates/ui-egui/src/i18n/gu.tsv +++ b/crates/ui-egui/src/i18n/gu.tsv @@ -4373,6 +4373,7 @@ arrowhead Feather પીંછું The Print Tiling tool placed the pages. પ્રિન્ટ ટાઇલિંગ ટૂલે પૃષ્ઠો ગોઠવ્યાં. The Scripts folder cannot be read સ્ક્રિપ્ટ્સ ફોલ્ડર વાંચી શકાતું નથી @msg The Startup Scripts folder cannot be read Startup Scripts ફોલ્ડર વાંચી શકાતું નથી +@msg The Startup Scripts folder was not read in full Startup Scripts ફોલ્ડર પૂરેપૂરું વાંચી શકાયું નથી Loading scripts… સ્ક્રિપ્ટ લોડ થઈ રહી છે… The Scripts folder is still being read સ્ક્રિપ્ટ્સ ફોલ્ડર હજી વંચાઈ રહ્યું છે The VECTORCRAFT_TITLEBAR environment variable chooses the title bar while it is set. જ્યારે VECTORCRAFT_TITLEBAR એન્વાયર્નમેન્ટ વેરિએબલ સેટ હોય ત્યારે તે ટાઇટલ બાર પસંદ કરે છે. diff --git a/crates/ui-egui/src/i18n/hi.tsv b/crates/ui-egui/src/i18n/hi.tsv index 91872f2807..77c21cba24 100644 --- a/crates/ui-egui/src/i18n/hi.tsv +++ b/crates/ui-egui/src/i18n/hi.tsv @@ -7588,6 +7588,7 @@ arrowhead Feather पंख Some scripts were not listed कुछ स्क्रिप्ट सूचीबद्ध नहीं की गईं The Scripts folder cannot be read Scripts फ़ोल्डर पढ़ा नहीं जा सकता @msg The Startup Scripts folder cannot be read Startup Scripts फ़ोल्डर पढ़ा नहीं जा सकता +@msg The Startup Scripts folder was not read in full Startup Scripts फ़ोल्डर पूरा नहीं पढ़ा गया Loading scripts… स्क्रिप्ट लोड हो रही हैं… The Scripts folder is still being read Scripts फ़ोल्डर अभी भी पढ़ा जा रहा है @msg the script's run is no longer available स्क्रिप्ट का रन अब उपलब्ध नहीं है diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index 4cdebb6b6c..27cfa3a865 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -5767,6 +5767,7 @@ imageTrace Outline Körvonal Some scripts were not listed Néhány szkript nem szerepel a listában The Scripts folder cannot be read A Scripts mappa nem olvasható @msg The Startup Scripts folder cannot be read A Startup Scripts mappa nem olvasható +@msg The Startup Scripts folder was not read in full A Startup Scripts mappa nem lett teljesen beolvasva Loading scripts… Szkriptek betöltése… The Scripts folder is still being read A Scripts mappa olvasása még tart @msg the script's run is no longer available a parancsfájl futása már nem érhető el diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index 56c282c700..eef6337eff 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -696,6 +696,7 @@ Some scripts were not listed Beberapa skrip tidak dicantumkan The Scripts folder cannot be read Folder Scripts tidak dapat dibaca @msg The Startup Scripts folder cannot be read Folder Startup Scripts tidak dapat dibaca +@msg The Startup Scripts folder was not read in full Folder Startup Scripts tidak terbaca seluruhnya Loading scripts… Memuat skrip… The Scripts folder is still being read Folder Scripts masih dibaca Other Script… Skrip lain… diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index 30d3c17b9e..0a72a85ce9 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -4973,6 +4973,7 @@ axis Both Entrambi Some scripts were not listed Alcuni script non sono stati elencati The Scripts folder cannot be read Impossibile leggere la cartella Scripts @msg The Startup Scripts folder cannot be read Impossibile leggere la cartella Startup Scripts +@msg The Startup Scripts folder was not read in full La cartella Startup Scripts non è stata letta per intero Loading scripts… Caricamento degli script… The Scripts folder is still being read La cartella Scripts è ancora in lettura @msg the script's run is no longer available l'esecuzione dello script non è più disponibile diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index 1d027fe166..f87051ba67 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -5799,6 +5799,7 @@ variable-list-end {0}, {1} {0}、{1} Some scripts were not listed 一部のスクリプトは一覧に表示されていません The Scripts folder cannot be read Scripts フォルダーを読み込めません @msg The Startup Scripts folder cannot be read Startup Scripts フォルダーを読み込めません +@msg The Startup Scripts folder was not read in full Startup Scripts フォルダーをすべて読み込めませんでした Loading scripts… スクリプトを読み込み中… The Scripts folder is still being read Scripts フォルダーをまだ読み込んでいます @msg the script's run is no longer available スクリプトの実行は利用できなくなりました diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index dcaefd804f..ffe4e8d93c 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -8468,6 +8468,7 @@ imageTrace Outline კონტური Some scripts were not listed ზოგიერთი სკრიპტი არ არის ჩამოთვლილი The Scripts folder cannot be read Scripts საქაღალდის წაკითხვა შეუძლებელია @msg The Startup Scripts folder cannot be read Startup Scripts საქაღალდის წაკითხვა შეუძლებელია +@msg The Startup Scripts folder was not read in full Startup Scripts საქაღალდე ბოლომდე ვერ წაიკითხა Loading scripts… სკრიპტების ჩატვირთვა… The Scripts folder is still being read Scripts საქაღალდე ჯერ კიდევ იკითხება @msg the script's run is no longer available სკრიპტის გაშვება აღარ არის ხელმისაწვდომი diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index f3194761a7..837d0783b5 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -5728,6 +5728,7 @@ variable-list-end {0}, {1} {0} 및 {1} Some scripts were not listed 일부 스크립트가 나열되지 않았습니다 The Scripts folder cannot be read Scripts 폴더를 읽을 수 없습니다 @msg The Startup Scripts folder cannot be read Startup Scripts 폴더를 읽을 수 없습니다 +@msg The Startup Scripts folder was not read in full Startup Scripts 폴더를 모두 읽지 못했습니다 Loading scripts… 스크립트 불러오는 중… The Scripts folder is still being read Scripts 폴더를 아직 읽는 중입니다 @msg the script's run is no longer available 스크립트 실행을 더 이상 사용할 수 없습니다 diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index 095b74c876..557309636f 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -666,6 +666,7 @@ liquify-list-end {0}, {1} {0} en {1} Some scripts were not listed Sommige scripts zijn niet weergegeven The Scripts folder cannot be read De map Scripts kan niet worden gelezen @msg The Startup Scripts folder cannot be read De map Startup Scripts kan niet worden gelezen +@msg The Startup Scripts folder was not read in full De map Startup Scripts is niet volledig gelezen Loading scripts… Scripts laden… The Scripts folder is still being read De map Scripts wordt nog gelezen Other Script… Ander script… diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index 90c5f96f7a..3b2248e78d 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -5078,6 +5078,7 @@ imageTrace Outline Kontur Some scripts were not listed Niektóre skrypty nie zostały wyświetlone The Scripts folder cannot be read Nie można odczytać folderu Scripts @msg The Startup Scripts folder cannot be read Nie można odczytać folderu Startup Scripts +@msg The Startup Scripts folder was not read in full Folder Startup Scripts nie został odczytany w całości Loading scripts… Wczytywanie skryptów… The Scripts folder is still being read Folder Scripts jest nadal odczytywany @msg the script's run is no longer available uruchomienie skryptu nie jest już dostępne diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index 8fc5caf929..2c29cdd4ed 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -6117,6 +6117,7 @@ variable-list-end {0}, {1} {0} e {1} Some scripts were not listed Alguns scripts não foram listados The Scripts folder cannot be read Não é possível ler a pasta Scripts @msg The Startup Scripts folder cannot be read Não é possível ler a pasta Startup Scripts +@msg The Startup Scripts folder was not read in full A pasta Startup Scripts não foi lida por completo Loading scripts… Carregando scripts… The Scripts folder is still being read A pasta Scripts ainda está sendo lida @msg the script's run is no longer available a execução do script não está mais disponível diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index 28e8d37183..22b5fc1adf 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -4949,6 +4949,7 @@ axis Both Оба Some scripts were not listed Некоторые сценарии не показаны The Scripts folder cannot be read Не удалось прочитать папку Scripts @msg The Startup Scripts folder cannot be read Не удалось прочитать папку Startup Scripts +@msg The Startup Scripts folder was not read in full Папка Startup Scripts прочитана не полностью Loading scripts… Загрузка сценариев… The Scripts folder is still being read Папка Scripts ещё читается @msg the script's run is no longer available выполнение скрипта больше недоступно diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index 9f9f6601b1..0cdbc66e4b 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -4811,6 +4811,7 @@ axis Both Båda Some scripts were not listed Vissa skript visas inte i listan The Scripts folder cannot be read Mappen Scripts kan inte läsas @msg The Startup Scripts folder cannot be read Mappen Startup Scripts kan inte läsas +@msg The Startup Scripts folder was not read in full Mappen Startup Scripts lästes inte in helt Loading scripts… Läser in skript… The Scripts folder is still being read Mappen Scripts läses fortfarande @msg the script's run is no longer available skriptets körning är inte längre tillgänglig diff --git a/crates/ui-egui/src/i18n/tests.rs b/crates/ui-egui/src/i18n/tests.rs index 2ca2c76e03..9148c44d46 100644 --- a/crates/ui-egui/src/i18n/tests.rs +++ b/crates/ui-egui/src/i18n/tests.rs @@ -717,6 +717,19 @@ fn compound_shape_no_area_warning_is_translated() { } } +/// The status bar's notes for a Startup Scripts folder that was not read in full or that cannot be +/// read, which the message scan doesn't read, are translated in each language of +/// [`COMPLETE_MESSAGES`]. +#[test] +fn startup_scripts_folder_notes_are_translated() { + for note in [crate::script_runs::STARTUP_TRUNCATED, crate::script_runs::STARTUP_UNREADABLE] { + for code in COMPLETE_MESSAGES { + let lang = Lang::from_code(code).expect("registered"); + assert_ne!(message(lang, note), note, "{code}: {note}"); + } + } +} + /// The Save PDF dialog's Save Summary… button and `ui.pdfSummary.save`'s error when no such /// dialog is open. #[test] diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index 0388a17783..5e64121178 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -4671,6 +4671,7 @@ axis Both Her İkisi Some scripts were not listed Bazı komut dosyaları listelenmedi The Scripts folder cannot be read Scripts klasörü okunamıyor @msg The Startup Scripts folder cannot be read Startup Scripts klasörü okunamıyor +@msg The Startup Scripts folder was not read in full Startup Scripts klasörü tamamen okunamadı Loading scripts… Betikler yükleniyor… The Scripts folder is still being read Scripts klasörü hâlâ okunuyor @msg the script's run is no longer available betiğin çalıştırması artık kullanılamıyor diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index 60f7356d36..f2daddc628 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -4957,6 +4957,7 @@ axis Both Обидві Some scripts were not listed Деякі сценарії не показано The Scripts folder cannot be read Не вдалося прочитати папку Scripts @msg The Startup Scripts folder cannot be read Не вдалося прочитати папку Startup Scripts +@msg The Startup Scripts folder was not read in full Папку Startup Scripts прочитано не повністю Loading scripts… Завантаження сценаріїв… The Scripts folder is still being read Папка Scripts ще читається @msg the script's run is no longer available виконання скрипта більше не доступне diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index d1cd5382c6..adc17de37a 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -5435,6 +5435,7 @@ theme Appearance Giao diện Some scripts were not listed Một số tập lệnh không được liệt kê The Scripts folder cannot be read Không thể đọc thư mục Scripts @msg The Startup Scripts folder cannot be read Không thể đọc thư mục Startup Scripts +@msg The Startup Scripts folder was not read in full Không đọc được toàn bộ thư mục Startup Scripts Loading scripts… Đang tải tập lệnh… The Scripts folder is still being read Thư mục Scripts vẫn đang được đọc @msg the script's run is no longer available lần chạy tập lệnh không còn khả dụng diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index b9db272073..64c72b7692 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -5464,6 +5464,7 @@ imageTrace Outline 轮廓 Some scripts were not listed 部分脚本未列出 The Scripts folder cannot be read 无法读取 Scripts 文件夹 @msg The Startup Scripts folder cannot be read 无法读取 Startup Scripts 文件夹 +@msg The Startup Scripts folder was not read in full 未能完整读取 Startup Scripts 文件夹 Loading scripts… 正在载入脚本… The Scripts folder is still being read 仍在读取 Scripts 文件夹 @msg the script's run is no longer available 脚本运行已不可用 diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index 0b4184b239..beefe6be89 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -2809,6 +2809,7 @@ file-filter Templates 範本 Some scripts were not listed 部分指令碼未列出 The Scripts folder cannot be read 無法讀取 Scripts 資料夾 @msg The Startup Scripts folder cannot be read 無法讀取 Startup Scripts 資料夾 +@msg The Startup Scripts folder was not read in full 未能完整讀取 Startup Scripts 資料夾 Loading scripts… 正在載入指令碼… The Scripts folder is still being read 仍在讀取 Scripts 資料夾 @msg the script's run is no longer available 指令碼執行已無法使用 diff --git a/crates/ui-egui/src/script_runs.rs b/crates/ui-egui/src/script_runs.rs index 034daa9672..7ab43f4db7 100644 --- a/crates/ui-egui/src/script_runs.rs +++ b/crates/ui-egui/src/script_runs.rs @@ -46,13 +46,56 @@ pub fn poll(app: &mut VectorcraftApp) { } Err(e) => failed(app, e.to_string()), } + startup_failures(app); app.sync_views(); } -/// Shows each run `script.startup.run` queued that could not start. +/// Shows each run `script.startup.run` queued that could not start ([`add_notes`]), and once the +/// round has no run left, the round's notes again ([`end_round`]). fn startup_failures(app: &mut VectorcraftApp) { - for (name, error) in app.session.take_startup_failures() { - app.status(format!("{name}: {error}")); + let failures: Vec = app.session.take_startup_failures().into_iter().map(|(name, error)| format!("{name}: {error}")).collect(); + if app.session.script_running() { + add_notes(app, failures); + } else { + app.ui.startup_notes.extend(failures); + end_round(app); + } +} + +/// Adds `notes` to those of the startup scripts' round under way and shows them all +/// ([`show_notes`]); a round with no run left keeps none. +fn add_notes(app: &mut VectorcraftApp, notes: Vec) { + if notes.is_empty() { + return; + } + app.ui.startup_notes.extend(notes); + show_notes(app, app.ui.startup_notes.clone()); + if !app.session.script_running() { + app.ui.startup_notes.clear(); + } +} + +/// When the startup scripts' round has notes and its last run has ended: shows them again, before +/// the message that run ended with and its own notes, so a later message does not hide them. +fn end_round(app: &mut VectorcraftApp) { + if app.ui.startup_notes.is_empty() { + return; + } + let mut notes = std::mem::take(&mut app.ui.startup_notes); + match app.ui.status_notes.take() { + Some((status, more)) if status == app.ui.status && more == notes => {} + Some((status, more)) if status == app.ui.status && !more.is_empty() => notes.extend(more), + _ if app.ui.status.is_empty() || notes.contains(&app.ui.status) => {} + _ => notes.push(app.ui.status.clone()), + } + show_notes(app, notes); +} + +/// Shows the first of `notes` in the status bar, and keeps them all for its hover, which lists +/// them when there are several. Without notes the status bar keeps its message. +fn show_notes(app: &mut VectorcraftApp, notes: Vec) { + if let Some(first) = notes.first().cloned() { + crate::io::show_with_notes(app, first, notes); } } @@ -90,39 +133,55 @@ fn ask(app: &mut VectorcraftApp) -> bool { /// Runs the script of `params` (`script.run`'s) that the person chose from File › Scripts, after /// the startup scripts when General › Run Startup Scripts is on (`script.startup.run`). A startup -/// script that cannot start shows in the status bar. +/// script that cannot start, a listing of the Startup Scripts folder that was not read in full, and +/// a folder that is there and cannot be read show in the status bar ([`reply_notes`]). pub(crate) fn run_chosen(app: &mut VectorcraftApp, params: Value) -> Result { if app.session.startup_skip().is_some() { return app.run("script.run", params); } let reply = app.run("script.startup.run", json!({"reason": "menu", "then": params}))?; - reply_failures(app, &reply); + reply_notes(app, &reply); Ok(reply) } -/// Shows each startup script that a `script.startup.run` reply names under `failed`: the queued -/// runs that could not start before the first one did. -fn reply_failures(app: &mut VectorcraftApp, reply: &Value) { - for failed in reply["failed"].as_array().into_iter().flatten() { - let (name, error) = (failed["name"].as_str().unwrap_or_default(), failed["error"].as_str().unwrap_or_default()); - app.status(format!("{name}: {error}")); +/// Starts the notes of a startup scripts' round with what its `script.startup.run` reply says was +/// left out ([`add_notes`]): each startup script it names under `failed` (the queued runs that +/// could not start before the first one did), then a listing that was not read in full +/// (`truncated`) or a folder that cannot be read (`unreadable`). The notes show again when the +/// round's last run ends ([`end_round`]). +pub(crate) fn reply_notes(app: &mut VectorcraftApp, reply: &Value) { + app.ui.startup_notes.clear(); + let mut notes: Vec = reply["failed"] + .as_array() + .into_iter() + .flatten() + .map(|failed| format!("{}: {}", failed["name"].as_str().unwrap_or_default(), failed["error"].as_str().unwrap_or_default())) + .collect(); + if reply["truncated"] == true { + notes.push(STARTUP_TRUNCATED.to_string()); } + if reply["unreadable"] == true { + notes.push(STARTUP_UNREADABLE.to_string()); + } + add_notes(app, notes); } +/// The status bar's note when a listing of the Startup Scripts folder stopped at a limit, left out +/// scripts past its limit or skipped an entry it could not read. +pub(crate) const STARTUP_TRUNCATED: &str = "The Startup Scripts folder was not read in full"; +/// The status bar's note when the Startup Scripts folder is there and cannot be read. +pub(crate) const STARTUP_UNREADABLE: &str = "The Startup Scripts folder cannot be read"; + /// When the app has started, out of Safe Mode: the startup scripts run when General › Run Startup -/// Scripts is on (`script.startup.run`). A failure to start them, or a Startup Scripts folder that -/// is there and cannot be read, shows in the status bar. +/// Scripts is on (`script.startup.run`). A failure to start them, a listing of the folder that was +/// not read in full, or a Startup Scripts folder that is there and cannot be read shows in the +/// status bar ([`reply_notes`]). pub fn run_at_launch(app: &mut VectorcraftApp) { if app.session.startup_skip().is_some() { return; } match app.run("script.startup.run", json!({"reason": "launch"})) { - Ok(reply) => { - reply_failures(app, &reply); - if reply["unreadable"] == true { - app.status("The Startup Scripts folder cannot be read"); - } - } + Ok(reply) => reply_notes(app, &reply), Err(e) => app.status(e), } } diff --git a/crates/ui-egui/src/state.rs b/crates/ui-egui/src/state.rs index f8bce4e088..29856b426d 100644 --- a/crates/ui-egui/src/state.rs +++ b/crates/ui-egui/src/state.rs @@ -670,6 +670,11 @@ pub struct UiState { /// Not saved. #[serde(skip)] pub status_notes: Option<(String, Vec)>, + /// What the startup scripts' round under way left out ([`crate::script_runs`]): the runs that + /// could not start and the notes on the Startup Scripts folder, shown again when its last run + /// ends. Not saved. + #[serde(skip)] + pub startup_notes: Vec, pub palette_open: bool, pub palette_query: String, /// Set when the palette's shortcut, its command or the search icon opens or closes the palette, @@ -1369,6 +1374,7 @@ impl Default for UiState { replace_font_warning: None, last_find: None, status_notes: None, + startup_notes: Vec::new(), palette_open: false, palette_query: String::new(), palette_toggled: false, diff --git a/crates/ui-egui/src/tests/scripts_menu.rs b/crates/ui-egui/src/tests/scripts_menu.rs index e6cc2896cd..dc815c3c64 100644 --- a/crates/ui-egui/src/tests/scripts_menu.rs +++ b/crates/ui-egui/src/tests/scripts_menu.rs @@ -679,11 +679,14 @@ fn a_menu_run_after_a_first_startup_script_that_cannot_start_shows_it_and_runs_t app.run("prefs.set", json!({"key": "runStartupScripts", "value": true})).unwrap(); app.status("before"); menus::run_ui_command(&mut app, "ui.runScript", &json!({ "source": DRAW, "name": "chosen" })).unwrap().unwrap(); - assert_eq!(app.ui.status, format!("0.jsx: {}", vectorcraft_engine::cmd::scripts::TOO_LARGE)); + let shown = format!("0.jsx: {}", vectorcraft_engine::cmd::scripts::TOO_LARGE); + assert_eq!(app.ui.status, shown); finish(&mut app); assert_eq!(started(&app), ["0.jsx", "chosen"]); assert_eq!(objects(&app), 2); - assert_eq!(app.ui.status, "Ran chosen"); + // The failure stays in sight when the chosen script ends, with its message in the hover. + assert_eq!(app.ui.status, shown); + assert_eq!(app.ui.status_notes, Some((shown.clone(), vec![shown, "Ran chosen".to_string()]))); let _ = std::fs::remove_dir_all(dir); } @@ -730,6 +733,81 @@ fn a_startup_scripts_folder_that_cannot_be_read_shows_in_the_status_bar_at_launc let _ = std::fs::remove_dir_all(dir); } +#[test] +fn a_menu_run_with_a_startup_scripts_folder_that_cannot_be_read_says_so_and_runs_the_chosen_script() { + let dir = folder("startup-menu-unreadable"); + let mut app = app(&dir); + let startup = dir.join("Startup Scripts"); + std::fs::write(&startup, "not a folder").unwrap(); + app.session.attach_startup_scripts_dir(startup); + app.session.prefs.show_external_script_warning = false; + app.run("prefs.set", json!({"key": "runStartupScripts", "value": true})).unwrap(); + app.status("before"); + menus::run_ui_command(&mut app, "ui.runScript", &json!({ "source": DRAW, "name": "chosen" })).unwrap().unwrap(); + let note = script_runs::STARTUP_UNREADABLE.to_string(); + assert_eq!(app.ui.status, note); + finish(&mut app); + assert_eq!(started(&app), ["chosen"]); + assert_eq!(app.ui.status, note, "the note stays in sight when the chosen script ends"); + assert_eq!(app.ui.status_notes, Some((note.clone(), vec![note, "Ran chosen".to_string()]))); + let _ = std::fs::remove_dir_all(dir); +} + +/// `dir`'s `Startup Scripts` folder, attached to `app`, holding one more entry than a listing reads +/// and no script. +fn overfull_startup_folder(app: &mut VectorcraftApp, dir: &std::path::Path) { + let startup = dir.join("Startup Scripts"); + std::fs::create_dir_all(&startup).unwrap(); + for n in 0..=vectorcraft_engine::script::folder::Limits::default().entries { + std::fs::write(startup.join(format!("{n}.txt")), "").unwrap(); + } + app.session.attach_startup_scripts_dir(startup); +} + +#[test] +fn a_startup_scripts_folder_not_read_in_full_shows_in_the_status_bar_at_launch_and_after_a_menu_run() { + let dir = folder("startup-truncated"); + let mut app = app(&dir); + overfull_startup_folder(&mut app, &dir); + app.session.prefs.show_external_script_warning = false; + app.run("prefs.set", json!({"key": "runStartupScripts", "value": true})).unwrap(); + let note = "The Startup Scripts folder was not read in full"; + app.status("before"); + script_runs::run_at_launch(&mut app); + assert_eq!(app.ui.status, note); + assert!(!app.session.script_running()); + app.status("before"); + menus::run_ui_command(&mut app, "ui.runScript", &json!({ "source": DRAW, "name": "chosen" })).unwrap().unwrap(); + assert_eq!(app.ui.status, note); + finish(&mut app); + assert_eq!(started(&app), ["chosen"]); + assert_eq!(app.ui.status, note, "the note stays in sight when the chosen script ends"); + assert_eq!(app.ui.status_notes, Some((note.to_string(), vec![note.to_string(), "Ran chosen".to_string()]))); + let de = crate::i18n::Lang::from_code("de").unwrap(); + assert_ne!(crate::i18n::message(de, note), note, "the note is translated"); + let _ = std::fs::remove_dir_all(dir); +} + +#[test] +fn startup_scripts_that_cannot_start_and_a_folder_not_read_in_full_all_stay_in_the_status_bar() { + let dir = folder("startup-notes"); + let mut app = app(&dir); + app.status("before"); + let reply = json!({ + "failed": [{"name": "0.jsx", "error": "too large"}, {"name": "1.jsx", "error": "cannot be read"}], + "truncated": true, + "unreadable": false, + }); + script_runs::reply_notes(&mut app, &reply); + let notes = vec!["0.jsx: too large".to_string(), "1.jsx: cannot be read".to_string(), script_runs::STARTUP_TRUNCATED.to_string()]; + assert_eq!(app.ui.status, "0.jsx: too large", "the first note shows"); + assert_eq!(app.ui.status_notes, Some((app.ui.status.clone(), notes)), "the hover lists every note"); + // A reply with nothing left out keeps the message. + script_runs::reply_notes(&mut app, &json!({"failed": [], "truncated": false, "unreadable": false})); + assert_eq!(app.ui.status, "0.jsx: too large"); + let _ = std::fs::remove_dir_all(dir); +} + #[test] fn a_first_read_that_ends_without_a_listing_says_the_folder_cannot_be_read_and_the_next_read_tries_again() { let dir = folder("lost"); diff --git a/docs/mcp.md b/docs/mcp.md index 761ad4a579..4f96dfd189 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -3174,8 +3174,12 @@ The rest of this section is VectorCraft's own rules: - Only the folder's own `.jsx` files run, never its subfolders. Links, names that start with a dot, files Windows marks hidden or system, names longer than 255 bytes and other file types are left out. A listing stops at 2,048 folder - entries, 512 scripts or 250 ms. A folder that is missing runs nothing. At launch, when the folder is there and cannot - be read, or a file is where the folder should be, the status bar says that the folder cannot be read. + entries or 250 ms and holds at most 512 scripts. When it stops at a limit, leaves out scripts past 512 or skips an + entry it cannot read, the status bar says that the folder was not read in full. A folder that is missing runs + nothing. At launch and before a chosen script, when the folder is there and cannot be read, or a file is where the + folder should be, the status bar says that the folder cannot be read. +- These two notes, and the names of startup scripts that could not start, stay in the status bar after the last run + ends: the status bar shows the first of them, and its hover lists them all, then the last run's message. - The scripts run one at a time, sorted by name without regard to case, then by name. Each runs as `script.run` runs a file, with the same limits, and each that changes a document adds its own Run Script undo step. The chosen script runs after the last of them. From 909c169afe0eadba5610d4e4e155e1bea793f6e4 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 22 Nov 2026 08:06:13 -0800 Subject: [PATCH 061/151] Scripts: queued startup runs keep the file access scope of the request that queued them In the app, script.startup.run starts only the first queued run inside the request; the later startup scripts and the chosen script start from the frame loop. Each of them now starts, and its file is read, in the scope captured when the queue was built, so a confined request's automation roots apply to every run it queued. --- crates/engine/src/cmd/scripts.rs | 11 +++++++++-- crates/engine/src/lib.rs | 3 +++ crates/engine/src/script/mod.rs | 1 + crates/engine/src/session/documents.rs | 1 + crates/engine/tests/script_startup.rs | 27 ++++++++++++++++++++++++++ 5 files changed, 41 insertions(+), 2 deletions(-) diff --git a/crates/engine/src/cmd/scripts.rs b/crates/engine/src/cmd/scripts.rs index 0484e170e0..c363fc4281 100644 --- a/crates/engine/src/cmd/scripts.rs +++ b/crates/engine/src/cmd/scripts.rs @@ -449,17 +449,20 @@ impl Session { pub(crate) fn start_queued(&mut self) -> Option { // Held aside while a run starts, so that the queue does not count as a running script then. let mut queue = std::mem::take(&mut self.script_queue); + // Each run starts in the file access scope of the request that queued it, which the run + // keeps, and not in the scope of the frame that starts it. + let scope = self.script_queue_scope.clone().unwrap_or_else(crate::file_access::ScopeHandle::capture); let mut reply = None; while self.script_key.is_none() { let Some(next) = queue.pop_front() else { break }; match next { script::startup::Queued::Startup { path, fuel } => { - if let Err(e) = self.start_startup(&path, fuel) { + if let Err(e) = scope.clone().run(|| self.start_startup(&path, fuel)) { self.startup_failures.push((file_name_of(&path), e)); } } script::startup::Queued::Then(params) => { - match run(self, ¶ms) { + match scope.clone().run(|| run(self, ¶ms)) { Ok(_) if self.script_key.is_some() => {} Ok(v) => reply = Some(v), Err(e) => self.startup_failures.push((then_name(¶ms), e.to_string())), @@ -468,6 +471,9 @@ impl Session { } } } + if queue.is_empty() { + self.script_queue_scope = None; + } self.script_queue = queue; reply } @@ -553,6 +559,7 @@ fn startup_run(s: &mut Session, p: &Value) -> Result { if s.script_frames { s.script_queue = scripts.into_iter().map(|path| script::startup::Queued::Startup { path, fuel }).chain(then.map(script::startup::Queued::Then)).collect(); + s.script_queue_scope = Some(crate::file_access::ScopeHandle::capture()); let queued = s.script_queue.len(); s.startup_failures.clear(); let then = s.start_queued(); diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 97bf9f1a48..6163d1abe0 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -314,6 +314,9 @@ pub struct Session { /// The runs `script.startup.run` queued in the app, each started when the run before it ends /// ([`Session::script_pump`]). pub(crate) script_queue: std::collections::VecDeque, + /// The file access scope of the request that queued [`Self::script_queue`], in which each queued + /// run starts and is read. + pub(crate) script_queue_scope: Option, /// While a startup script runs: the launch marker's entry naming it /// ([`vectorcraft_plugins::safe_mode::loading`]). pub(crate) startup_loading: Option, diff --git a/crates/engine/src/script/mod.rs b/crates/engine/src/script/mod.rs index d006f0500d..f877e867eb 100644 --- a/crates/engine/src/script/mod.rs +++ b/crates/engine/src/script/mod.rs @@ -1884,6 +1884,7 @@ impl Session { pub fn script_abandon(&mut self) -> bool { // The runs queued after it are not started. self.script_queue.clear(); + self.script_queue_scope = None; self.startup_ended(); let Some(key) = self.script_key.take() else { return false }; let Some(job) = JOBS.with(|jobs| jobs.borrow_mut().remove(&key.id)) else { diff --git a/crates/engine/src/session/documents.rs b/crates/engine/src/session/documents.rs index 7b58bba1fd..61df37240f 100644 --- a/crates/engine/src/session/documents.rs +++ b/crates/engine/src/session/documents.rs @@ -170,6 +170,7 @@ impl Session { script_runs: 0, script_frames: false, script_queue: Default::default(), + script_queue_scope: None, startup_loading: None, startup_failures: vec![], script_high_water: Default::default(), diff --git a/crates/engine/tests/script_startup.rs b/crates/engine/tests/script_startup.rs index f0135636d4..fca883cfc0 100644 --- a/crates/engine/tests/script_startup.rs +++ b/crates/engine/tests/script_startup.rs @@ -353,3 +353,30 @@ fn in_the_app_startup_scripts_that_cannot_start_are_in_the_reply() { assert_eq!(r["failed"], json!([{"name": "big.jsx", "error": vectorcraft_engine::cmd::scripts::TOO_LARGE}])); assert!(s.take_startup_failures().is_empty(), "the reply names them, so the status bar does not again"); } + +#[test] +fn in_the_app_every_queued_run_keeps_the_automation_roots_of_the_request_that_queued_it() { + let _f = fresh(); + let dir = tmp_dir("app-roots"); + // Writes a file in the run's temporary folder, which is outside the write roots below. + let source = "var ok; try { var t = new File(Folder.temp.fsName + '/t.txt'); ok = t.open('w'); t.close(); } catch (e) { ok = false; }\n\ + vc.log(ok ? 'wrote' : 'refused');"; + write(&dir, "a.jsx", source); + write(&dir, "b.jsx", source); + let roots = vectorcraft_engine::file_access::AutomationRoots::new(&[dir.as_path()], &[]).unwrap().unwrap(); + for confined in [false, true] { + let mut s = session(&dir); + s.script_frames = true; + let params = json!({"reason": "menu", "then": {"source": source, "name": "chosen"}}); + let mut request = || s.execute("script.startup.run", ¶ms).unwrap(); + let r = if confined { vectorcraft_engine::file_access::confine(Some(&roots), request) } else { request() }; + assert_eq!(r["queued"], json!(3)); + // The frames that start the later runs are outside the request. + while s.script_running() { + s.script_pump(); + } + assert_eq!(started(&s), ["a.jsx", "b.jsx", "chosen"]); + let want = if confined { "refused" } else { "wrote" }; + assert_eq!(console(&s, "log"), [want, want, want], "confined {confined}"); + } +} From 30eb12aba37a97ff2abc0894a4d1dcdc48165303 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 22 Nov 2026 08:15:47 -0800 Subject: [PATCH 062/151] JavaScript: generator functions, yield and yield* in ES2015 realms A realm made with Options::es2015 reads function* declarations and expressions, *name() methods in object literals, yield and yield*, as ECMA-262 11th edition sections 14.4 and 25.4 define them. A suspended generator keeps its frame in its object; next, return and throw on %GeneratorPrototype% push it back on the interpreter's frame stack, so a resumption takes fuel and counts against the frame limit, and return runs the finally blocks around the yield. Resuming a running generator throws a TypeError. yield* passes next, throw and return on to its iterator and closes one without throw before throwing a TypeError. %GeneratorFunction% is reached through a generator function's constructor. Outside generators, sloppy code still reads yield as a name, and a realm without the option reads function* as a syntax error. An engine that #targetengine kept from a .jsx run has no generator built-ins, so a generator function called there throws a TypeError. cargo xtask test262 runs the generator folders: 509 of 549 runs pass (94 of 96 before). Docs: docs/mcp.md, docs/target-app-parity.md. --- crates/engine/src/tests/script_run.rs | 27 ++ crates/js/src/ast.rs | 8 + crates/js/src/builtins.rs | 25 +- crates/js/src/builtins/generator.rs | 51 ++++ crates/js/src/builtins/iterator.rs | 2 +- crates/js/src/builtins/symbol.rs | 5 +- crates/js/src/bytecode.rs | 33 +++ crates/js/src/compiler.rs | 85 +++++- crates/js/src/generator.rs | 410 ++++++++++++++++++++++++++ crates/js/src/generator_tests.rs | 305 +++++++++++++++++++ crates/js/src/heap.rs | 24 +- crates/js/src/interp.rs | 83 +++++- crates/js/src/interp_tests.rs | 1 + crates/js/src/lib.rs | 16 +- crates/js/src/parser.rs | 156 ++++++++-- crates/js/src/realm.rs | 3 + crates/js/src/symbol.rs | 16 +- crates/js/tests/test262.rs | 100 +++++++ docs/mcp.md | 12 +- docs/target-app-parity.md | 3 +- 20 files changed, 1312 insertions(+), 53 deletions(-) create mode 100644 crates/js/src/builtins/generator.rs create mode 100644 crates/js/src/generator.rs create mode 100644 crates/js/src/generator_tests.rs diff --git a/crates/engine/src/tests/script_run.rs b/crates/engine/src/tests/script_run.rs index 7b0e4bc2f8..d6ca60461c 100644 --- a/crates/engine/src/tests/script_run.rs +++ b/crates/engine/src/tests/script_run.rs @@ -331,6 +331,33 @@ fn a_js_script_reads_ecmascript_2015_and_a_jsx_script_does_not() { let _ = std::fs::remove_dir_all(&dir); } +#[test] +fn a_js_script_runs_generators_and_a_jsx_script_does_not_read_them() { + let dir = fresh_folder("generators"); + let write = |name: &str, text: &str| { + let p = dir.join(name); + std::fs::write(&p, text).unwrap(); + p.to_string_lossy().into_owned() + }; + let mut s = two_docs(); + let path = |p: &str| json!({"path": p}); + let source = "function* ids(n) { for (let i = 0; i < n; i++) yield `id${i}`; }\n\ + function* all() { yield* ids(2); yield* [vc.document ? 'doc' : 'none']; return 'end'; }\n\ + const it = all(); let s;\nwhile (!(s = it.next()).done) vc.log(s.value);\nvc.log(s.value);\n"; + let r = s.execute("script.run", &path(&write("gen.js", source))).unwrap(); + assert_eq!(r["log"], json!(["id0", "id1", "doc", "end"]), "{r}"); + let e = s.execute("script.run", &path(&write("gen.jsx", "function* g() {}"))).unwrap_err().to_string(); + assert!(e.contains("SyntaxError"), "{e}"); + // `yield` stays a name in a `.jsx` script. + let r = s.execute("script.run", &path(&write("name.jsx", "var yield = 4; vc.log(yield);"))).unwrap(); + assert_eq!(r["log"], json!([4]), "{r}"); + // An engine a `.jsx` run made has no generator built-ins for a later `.js` run. + s.execute("script.run", &path(&write("keep.jsx", "#targetengine genkept\nvar a = 1;"))).unwrap(); + let e = s.execute("script.run", &path(&write("keep.js", "#targetengine genkept\nfunction* g() {}\ng();"))).unwrap_err().to_string(); + assert!(e.contains("TypeError"), "{e}"); + let _ = std::fs::remove_dir_all(&dir); +} + /// A new empty folder for test `name`. fn fresh_folder(name: &str) -> std::path::PathBuf { let dir = std::env::temp_dir().join(format!("vc-script-run-{name}-{}", std::process::id())); diff --git a/crates/js/src/ast.rs b/crates/js/src/ast.rs index c015e3fa38..c8fddfdcc2 100644 --- a/crates/js/src/ast.rs +++ b/crates/js/src/ast.rs @@ -218,6 +218,12 @@ pub enum Expr { /// `...expression` in an array literal or an argument list, and as the last of an arrow /// function's parenthesized parameters while they are read. Spread(ExprId), + /// `yield`, `yield expression` or (`delegate`) `yield* expression` in a generator function's + /// body (ECMA-262 2015 section 14.4). + Yield { + arg: Option, + delegate: bool, + }, } /// A piece of a template literal's text between its substitutions. @@ -393,6 +399,8 @@ pub struct Function { /// The function's code is strict mode code: its own directive prologue holds `"use strict"`, /// or the code around it is strict. pub strict: bool, + /// A generator function (`function*`, or `*name() {…}` in an object literal). + pub generator: bool, pub span: Span, } diff --git a/crates/js/src/builtins.rs b/crates/js/src/builtins.rs index 9fc8ba3539..9091441937 100644 --- a/crates/js/src/builtins.rs +++ b/crates/js/src/builtins.rs @@ -3,8 +3,9 @@ //! `Array`, the error constructors, `Math`, `JSON`, the global functions and constants, Annex //! B's `escape` and `unescape`, and the prototypes primitive values look properties up on, with //! `Boolean.prototype`'s `toString` and `valueOf`. `String`, `Number`, `RegExp` and `Date` are in -//! their own modules. A realm with [`crate::Options::es2015`] also has `Symbol` (in `symbol`) and -//! the iterators of arrays, strings and `arguments` objects (in `iterator`). +//! their own modules. A realm with [`crate::Options::es2015`] also has `Symbol` (in `symbol`), +//! the iterators of arrays, strings and `arguments` objects (in `iterator`), and the generator +//! objects' prototypes with `GeneratorFunction` (in `generator`). //! //! Every loop in a built-in takes a unit of fuel for each step, and every string, array, object //! or property it makes is checked against the heap limit before it is made, so no built-in can @@ -12,6 +13,7 @@ mod array; pub(crate) mod extensions; +mod generator; mod global; pub(crate) mod iterator; mod json; @@ -148,6 +150,7 @@ fn try_install(interp: &mut Interp) -> JsResult<()> { if interp.options.es2015 { symbol::install(interp, object)?; iterator::install(interp)?; + generator::install(interp, function)?; } if interp.options.e4x { crate::xml_builtins::install(interp)?; @@ -355,7 +358,7 @@ pub(crate) fn arg(args: &[Value], i: usize) -> Value { } fn unreachable_native(_: &mut Interp, _: Value, _: &[Value], _: bool) -> JsResult { - Err(Abrupt::Internal("call or apply reached its native body".into())) + Err(Abrupt::Internal("a built-in the interpreter runs itself reached its native body".into())) } fn throw_type_error(interp: &mut Interp, _: Value, _: &[Value], _: bool) -> JsResult { @@ -476,7 +479,13 @@ fn property_is_enumerable(interp: &mut Interp, this: Value, args: &[Value], _: b /// `Function(p1, …, body)` and `new Function(…)` (section 15.3.2.1): the source is read as /// `(function anonymous(p1,…\n) {\nbody\n})` and must be exactly that one function. fn function_ctor(interp: &mut Interp, _: Value, args: &[Value], _: bool) -> JsResult { - const HEAD: &str = "(function anonymous("; + create_dynamic_function(interp, args, false) +} + +/// CreateDynamicFunction (ECMA-262 11th edition, section 19.2.1.1.1) for `Function` and, with +/// `generator`, for `GeneratorFunction`, whose source is read as `(function* anonymous(…`. +pub(crate) fn create_dynamic_function(interp: &mut Interp, args: &[Value], generator: bool) -> JsResult { + let head: &str = if generator { "(function* anonymous(" } else { "(function anonymous(" }; const MID: &str = "\n) {\n"; const TAIL: &str = "\n})"; let mut parts = Vec::with_capacity(args.len()); @@ -488,12 +497,12 @@ fn function_ctor(interp: &mut Interp, _: Value, args: &[Value], _: bool) -> JsRe let total = parts .iter() .map(Str::len) - .chain([parts.len().saturating_sub(1), HEAD.len() + MID.len() + TAIL.len(), body.len()]) + .chain([parts.len().saturating_sub(1), head.len() + MID.len() + TAIL.len(), body.len()]) .fold(0usize, usize::saturating_add); interp.check_source_units(total).map_err(|e| interp.compile_error_to_abrupt(e))?; interp.prepare_source(total)?; let mut units = Vec::with_capacity(total); - units.extend(HEAD.encode_utf16()); + units.extend(head.encode_utf16()); for (i, p) in parts.iter().enumerate() { if i > 0 { units.push(u16::from(b',')); @@ -513,8 +522,8 @@ fn function_ctor(interp: &mut Interp, _: Value, args: &[Value], _: bool) -> JsRe }; let source = Rc::new(Source { lines: program.lines.clone(), text: units.into(), tag: interp.source_tag, strict_writes: interp.writes_mode() }); let code = match compile_constructed_function(&program, &source) { - Ok(Some(code)) => code, - Ok(None) => return Err(interp.throw(ErrorType::Syntax, "the parameters or body do not form one function")), + Ok(Some(code)) if code.generator == generator => code, + Ok(_) => return Err(interp.throw(ErrorType::Syntax, "the parameters or body do not form one function")), Err(CompileFail::Syntax(e)) => return Err(interp.throw(ErrorType::Syntax, &e.message)), Err(CompileFail::Internal(m)) => return Err(Abrupt::Internal(m)), }; diff --git a/crates/js/src/builtins/generator.rs b/crates/js/src/builtins/generator.rs new file mode 100644 index 0000000000..c8e46e09d6 --- /dev/null +++ b/crates/js/src/builtins/generator.rs @@ -0,0 +1,51 @@ +//! The generator built-ins (ECMA-262 11th edition, ): +//! `%GeneratorFunction%` with its `prototype` (sections 25.2.1 and 25.2.3) and +//! `%GeneratorPrototype%` with `next`, `return` and `throw` (section 25.4.1), which inherits +//! from `%IteratorPrototype%`. Installed in a realm with [`crate::Options::es2015`] only, after the +//! iterators. `GeneratorFunction` is not a global; a script reaches it through a generator +//! function's `constructor`. + +use super::{data, native, unreachable_native}; +use crate::generator::ResumeMode; +use crate::heap::{CONFIGURABLE, Class, HIDDEN, NativeKind, ObjId, Object, Prop}; +use crate::interp::{Interp, JsResult}; +use crate::value::Value; + +pub(super) fn install(interp: &mut Interp, function: ObjId) -> JsResult<()> { + let Some(to_string_tag) = interp.well_known(|w| &w.to_string_tag) else { return Ok(()) }; + let Some(mut objects) = interp.symbols.objects else { return Ok(()) }; + let object_proto = interp.intrinsics.object_proto; + let iterator_proto = interp.heap.object(objects.array_iterator_proto).and_then(|o| o.proto).unwrap_or(object_proto); + + let generator_proto = interp.heap.alloc_object(Object::new(Class::Ordinary, Some(iterator_proto))); + for (name, mode) in [("next", ResumeMode::Next), ("return", ResumeMode::Return), ("throw", ResumeMode::Throw)] { + let m = native(interp, name, unreachable_native, 1, NativeKind::Resume(mode), false)?; + data(interp, generator_proto, name, Value::Object(m), HIDDEN)?; + } + interp.define_sym(generator_proto, to_string_tag.clone(), Prop::Data { value: Value::str("Generator"), flags: CONFIGURABLE })?; + + let function_proto = interp.intrinsics.function_proto; + // %GeneratorFunction.prototype% is an ordinary object, not a function, that inherits from + // Function.prototype (section 25.2.3). + let generator_function_proto = interp.heap.alloc_object(Object::new(Class::Ordinary, Some(function_proto))); + data(interp, generator_function_proto, "prototype", Value::Object(generator_proto), CONFIGURABLE)?; + data(interp, generator_proto, "constructor", Value::Object(generator_function_proto), CONFIGURABLE)?; + interp.define_sym(generator_function_proto, to_string_tag, Prop::Data { value: Value::str("GeneratorFunction"), flags: CONFIGURABLE })?; + + let generator_function = native(interp, "GeneratorFunction", generator_function_ctor, 1, NativeKind::Plain, true)?; + if let Some(o) = interp.heap.object_mut(generator_function) { + o.proto = Some(function); + } + data(interp, generator_function, "prototype", Value::Object(generator_function_proto), 0)?; + data(interp, generator_function_proto, "constructor", Value::Object(generator_function), CONFIGURABLE)?; + + objects.generator_proto = generator_proto; + objects.generator_function_proto = generator_function_proto; + interp.symbols.objects = Some(objects); + Ok(()) +} + +/// `GeneratorFunction(p1, …, body)` and `new GeneratorFunction(…)` (section 25.2.1.1). +fn generator_function_ctor(interp: &mut Interp, _: Value, args: &[Value], _: bool) -> JsResult { + super::create_dynamic_function(interp, args, true) +} diff --git a/crates/js/src/builtins/iterator.rs b/crates/js/src/builtins/iterator.rs index 317b66ecc2..09462496a3 100644 --- a/crates/js/src/builtins/iterator.rs +++ b/crates/js/src/builtins/iterator.rs @@ -78,7 +78,7 @@ fn return_this(_: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult JsResult { +pub(crate) fn iter_result(interp: &mut Interp, value: Value, done: bool) -> JsResult { interp.rooted(std::slice::from_ref(&value), |i| i.reserve_heap(OBJECT_BYTES + 2 * PROP_BYTES))?; let proto = interp.intrinsics.object_proto; let o = interp.heap.alloc_object(Object::new(Class::Ordinary, Some(proto))); diff --git a/crates/js/src/builtins/symbol.rs b/crates/js/src/builtins/symbol.rs index b671f51e42..109493a03d 100644 --- a/crates/js/src/builtins/symbol.rs +++ b/crates/js/src/builtins/symbol.rs @@ -44,13 +44,16 @@ pub(super) fn install(interp: &mut Interp, object_ctor: ObjId) -> JsResult<()> { method(interp, object_ctor, "getOwnPropertySymbols", get_own_property_symbols, 1)?; let function_proto = interp.intrinsics.function_proto; let has_instance = sym_method(interp, function_proto, has_instance, "[Symbol.hasInstance]", function_has_instance, 1, 0)?; - // The iterator prototypes and `%ArrayProto_values%` are set when the iterators are installed. + // The iterator and generator prototypes and `%ArrayProto_values%` are set when the iterators + // and generators are installed. interp.symbols.objects = Some(Es2015Objects { symbol_proto: proto, array_iterator_proto: proto, string_iterator_proto: proto, array_values: has_instance, has_instance, + generator_proto: proto, + generator_function_proto: function_proto, }); Ok(()) } diff --git a/crates/js/src/bytecode.rs b/crates/js/src/bytecode.rs index 28db7edf3d..91f7cfa5f6 100644 --- a/crates/js/src/bytecode.rs +++ b/crates/js/src/bytecode.rs @@ -205,6 +205,29 @@ pub(crate) enum Op { ToStr, /// Pushes the template object of `templates[i]`, the same object for each evaluation. TemplateObject(u32), + /// Ends a generator function's call once its parameters are initialized: the frame becomes a + /// new generator object, which the call returns. The first `next` goes on after it. + GeneratorStart, + /// `value` → `received mode`: suspends the generator, giving its caller `{ value, done: false }` + /// (or, when true, the value itself, an iterator result from `yield*`'s delegate). It goes on + /// when the generator is resumed, with the value it was resumed with and how (0 `next`, 1 + /// `throw`, 2 `return`). + Yield(bool), + /// `received mode` → `received`: goes on for `next`, throws the value for `throw`, and jumps + /// with it for `return`. + Resume(u32), + /// `value` → `iterator next`: GetIterator (ECMA-262 11th edition, section 7.4.1). + GetIterator, + /// `iterator next received mode` → `iterator next mode method iterator received`, ready for + /// `Call(1)`: the delegate's `next`, `throw` or `return`. With `return` and no `return` method + /// it jumps with `iterator next received`; with `throw` and no `throw` method it closes the + /// iterator and throws a `TypeError` (section 14.4.14). + DelegateCall(u32), + /// `mode result` → `result` when the iterator result is not done; when it is, jumps with + /// `mode value`. A result that is not an object is a `TypeError`. + DelegateResult(u32), + /// `mode value` → `value`; for `return`, jumps with it. + DelegateDone(u32), } /// The names a block declares, entered with [`Op::PushBlock`]. @@ -299,6 +322,9 @@ pub(crate) struct Code { /// The function has default or rest parameters: its parameters start uninitialized, its /// code initializes them and then enters its body with [`Op::BodyEnv`]. pub(crate) param_init: bool, + /// The code is a generator function's: a call makes a generator object ([`Op::GeneratorStart`]), + /// and it is not a constructor. + pub(crate) generator: bool, } impl Code { @@ -381,6 +407,12 @@ fn effect(op: Op, finally_tables: &[Vec]) -> Result { Op::ArraySpread | Op::NewSpread => e(2, 1), Op::CallSpread(_) => e(3, 1), Op::ToStr => e(1, 1), + Op::GeneratorStart => e(0, 0), + Op::Yield(_) => e(1, 2), + Op::Resume(t) | Op::DelegateDone(t) => Effect { pops: 2, next: Some(1), jumps: vec![(t, 1)] }, + Op::GetIterator => e(1, 2), + Op::DelegateCall(t) => Effect { pops: 2, next: Some(4), jumps: vec![(t, 1)] }, + Op::DelegateResult(t) => Effect { pops: 2, next: Some(1), jumps: vec![(t, 2)] }, }) } @@ -415,6 +447,7 @@ fn check_indices(op: Op, code: &Code) -> Result<(), String> { Op::PushBlock(i) => check(i, code.scopes.len(), "scope"), Op::TemplateObject(i) => check(i, code.templates.len(), "template"), Op::RegExp(i) => check(i, code.regexps.len(), "regular expression"), + Op::GeneratorStart | Op::Yield(_) if !code.generator => Err("a generator instruction outside a generator function".into()), _ => Ok(()), } } diff --git a/crates/js/src/compiler.rs b/crates/js/src/compiler.rs index b5bdd16958..fe4c5cd95e 100644 --- a/crates/js/src/compiler.rs +++ b/crates/js/src/compiler.rs @@ -99,6 +99,8 @@ struct FnCompiler<'a> { block_funcs: HashSet, /// The function declarations in blocks whose names are also var-scoped (Annex B.3.3). annex: HashSet, + /// The code is a generator function's. + generator: bool, } /// The `var` names and function declarations a body hoists. @@ -146,6 +148,7 @@ impl<'a> FnCompiler<'a> { top_funcs: HashSet::new(), block_funcs: HashSet::new(), annex: HashSet::new(), + generator: false, } } @@ -268,12 +271,13 @@ impl<'a> FnCompiler<'a> { Stmt::Var(decls) => decls.iter().for_each(|d| add_var(&mut out, key_of(&d.name.name))), Stmt::Lexical(..) => {} Stmt::FunctionDecl(fid) => { - let Some(name) = self.ast.function(*fid).and_then(|f| f.name.as_ref()) else { + let Some((name, generator)) = self.ast.function(*fid).and_then(|f| Some((f.name.as_ref()?, f.generator))) else { return internal("function declaration without a name"); }; let k = key_of(&name.name); if self.es2015 && nested { - if !self.strict { + // Annex B.3.3 gives plain function declarations only a var binding too. + if !self.strict && !generator { annex.push((k, scope, id)); } } else { @@ -1195,10 +1199,73 @@ impl<'a> FnCompiler<'a> { self.emit(Op::XmlScopeGet); } Expr::XmlDescendants { .. } | Expr::XmlFilter { .. } => self.chain(id)?, + Expr::Yield { arg, delegate: false } => { + match arg { + Some(e) => self.expr(*e)?, + None => self.emit(Op::Undefined), + } + self.at(self.ast.expr_span(id).start); + self.emit(Op::Yield(false)); + self.resume_after_yield()?; + } + Expr::Yield { arg: Some(e), delegate: true } => self.yield_delegate(id, *e)?, + Expr::Yield { arg: None, delegate: true } => return internal("yield* without an operand"), } Ok(()) } + /// After a `Yield` that left `received mode`: goes on with the received value for `next`, + /// throws it for `throw`, and for `return` returns it through the `finally` blocks around. + fn resume_after_yield(&mut self) -> CResult<()> { + if !self.generator { + return internal("yield outside a generator function"); + } + let ret = self.new_label(); + let after = self.new_label(); + self.jump(Op::Resume, ret); + self.jump(Op::Jump, after); + self.bind(ret); + self.emit_exit(Exit::Return)?; + self.bind(after); + Ok(()) + } + + /// `yield* operand` (ECMA-262 11th edition, section 14.4.14): each `next`, `throw` and `return` + /// the generator is resumed with goes to the operand's iterator, each result it gives that is + /// not done is yielded as it is, and a done one gives the expression its value, or for a + /// `return` returns that value. + fn yield_delegate(&mut self, id: ExprId, operand: ExprId) -> CResult<()> { + if !self.generator { + return internal("yield outside a generator function"); + } + let d = self.depth; + self.expr(operand)?; + self.at(self.ast.expr_span(id).start); + self.emit(Op::GetIterator); + // The first step calls `next` with one argument, `undefined`: the spec starts with + // `received` as NormalCompletion(undefined) and calls `next` with « received.[[Value]] ». + self.emit(Op::Undefined); + self.push_number(0.0); + let (step, ret, done, end) = (self.new_label(), self.new_label(), self.new_label(), self.new_label()); + self.bind(step); + self.jump(Op::DelegateCall, ret); + self.emit(Op::Call(1)); + self.jump(Op::DelegateResult, done); + self.emit(Op::Yield(true)); + self.jump(Op::Jump, step); + self.bind(done); + self.depth = d + 4; + self.jump(Op::DelegateDone, ret); + self.emit(Op::PopUnder(2)); + self.jump(Op::Jump, end); + self.bind(ret); + self.depth = d + 3; + self.emit_exit(Exit::Return)?; + self.bind(end); + self.depth = d + 1; + Ok(()) + } + /// Pushes the nearest XML value in scope that holds the E4X name `name` of the expression /// `id`, then the name, as an assignment, update or `delete` uses them. fn xml_scope_ref(&mut self, id: ExprId, name: ExprId) -> CResult<()> { @@ -1718,7 +1785,11 @@ impl<'a> FnCompiler<'a> { | Op::JumpIfFalseKeep(t) | Op::JumpIfTrueKeep(t) | Op::ForInNext(t) - | Op::XmlFilterNext(t), + | Op::XmlFilterNext(t) + | Op::Resume(t) + | Op::DelegateCall(t) + | Op::DelegateResult(t) + | Op::DelegateDone(t), ) => *t = target, _ => return internal("patching an instruction that is not a jump"), } @@ -1762,6 +1833,7 @@ impl<'a> FnCompiler<'a> { arrow: meta.arrow, uses_this: self.uses_this, param_init: meta.param_init, + generator: self.generator, }; code.max_stack = verify(&code).map_err(CompileFail::Internal)?; Ok(Rc::new(code)) @@ -1792,6 +1864,7 @@ pub(crate) fn compile_function(ast: &Ast, fid: FunctionId, source: &Rc, let Some(f) = ast.function(fid) else { return internal("function out of range") }; let mut c = FnCompiler::new(ast, source, CodeKind::Function, f.strict, recursion); c.es2015 = es2015; + c.generator = f.generator; c.at(f.span.start); c.enter()?; let params: Vec = f.params.iter().map(|p| key_of(&p.name)).collect(); @@ -1828,6 +1901,12 @@ pub(crate) fn compile_function(ast: &Ast, fid: FunctionId, source: &Rc, } c.emit(Op::BodyEnv); } + if f.generator { + // The call has bound the arguments and run the default values; the body waits for + // the first `next` (ECMA-262 2015 section 14.4.11). + c.at(f.span.start); + c.emit(Op::GeneratorStart); + } c.stmts(&f.body)?; c.at(f.span.end.saturating_sub(1)); c.emit(Op::Undefined); diff --git a/crates/js/src/generator.rs b/crates/js/src/generator.rs new file mode 100644 index 0000000000..5169dcb2d0 --- /dev/null +++ b/crates/js/src/generator.rs @@ -0,0 +1,410 @@ +//! Generator objects (ECMA-262 11th edition, , +//! sections 14.4 and 25.4), in a realm with [`crate::Options::es2015`]. +//! +//! A call to a generator function runs its parameters' initialization and stops at +//! [`Op::GeneratorStart`]: its frame, with the operands above the frame's base and the `finally` +//! blocks it is inside, moves into a new generator object, which the call returns. `next`, +//! `return` and `throw` push the frame back on the interpreter's frame stack and go on in the same +//! loop, so a generator driven from JavaScript uses no Rust stack, and each resumption takes a unit +//! of fuel and counts against the frame limit. `yield` moves the frame back into the object. A +//! suspended generator's frame is reachable only through its object, so the collector keeps it +//! while the object is reachable and frees it with the object. +//! +//! [`Op::GeneratorStart`]: crate::bytecode::Op::GeneratorStart + +use std::rc::Rc; + +use crate::LimitKind; +use crate::builtins::iterator::iter_result; +use crate::bytecode::Code; +use crate::heap::{Class, EnvId, OBJECT_BYTES, ObjId, Object, key}; +use crate::interp::{Abrupt, Frame, Interp, JsResult, Prepared, ThrowSite, internal}; +use crate::value::Value; + +/// How a generator is resumed: by `next`, `throw` or `return` (sections 25.4.1.3 and 25.4.1.4). +/// The code after a `yield` reads it as the number [`ResumeMode::number`] gives. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum ResumeMode { + Next, + Throw, + Return, +} + +impl ResumeMode { + fn number(self) -> f64 { + match self { + ResumeMode::Next => 0.0, + ResumeMode::Throw => 1.0, + ResumeMode::Return => 2.0, + } + } + + fn of(v: &Value) -> JsResult { + match v { + Value::Number(n) if *n == 0.0 => Ok(ResumeMode::Next), + Value::Number(n) if *n == 1.0 => Ok(ResumeMode::Throw), + Value::Number(n) if *n == 2.0 => Ok(ResumeMode::Return), + _ => internal("a resumption mode that is not one"), + } + } +} + +/// The estimated bytes of a suspended generator's frame besides its operands. +const GENERATOR_BYTES: usize = 128; + +/// The estimated bytes of each operand and `finally` entry a suspended frame holds. +const SLOT_BYTES: usize = 16; + +/// A generator's frame while it is suspended: what [`Frame`] holds, with the operands above its +/// base and its `finally` entries, their stack slots counted from its base. +#[derive(Clone)] +pub(crate) struct SavedFrame { + pub(crate) code: Rc, + pc: usize, + pub(crate) env: EnvId, + pub(crate) var_env: EnvId, + env_depth: u32, + pub(crate) this: Value, + pub(crate) callee: Option, + pub(crate) completion: Value, + pub(crate) stack: Vec, + /// [`Interp::finally_sites`] entries. + pub(crate) sites: Vec<(ThrowSite, usize)>, + /// [`Interp::finally_marks`] entries. + pub(crate) marks: Vec<(ObjId, u32, usize)>, +} + +/// A generator's [[GeneratorState]] (section 25.4.3), with its frame while it is suspended. +#[derive(Clone)] +pub(crate) enum GenState { + SuspendedStart(SavedFrame), + SuspendedYield(SavedFrame), + Executing, + Completed, +} + +impl GenState { + /// The suspended frame, if the generator is suspended. + pub(crate) fn saved(&self) -> Option<&SavedFrame> { + match self { + GenState::SuspendedStart(s) | GenState::SuspendedYield(s) => Some(s), + GenState::Executing | GenState::Completed => None, + } + } +} + +/// The bytes a suspended frame adds to its generator object, which a collection counts. +pub(crate) fn saved_bytes(s: &SavedFrame) -> usize { + GENERATOR_BYTES.saturating_add(SLOT_BYTES.saturating_mul(s.stack.len().saturating_add(s.sites.len()).saturating_add(s.marks.len()))) +} + +/// A generator resumed by `next`, `return` or `throw`, ready to be pushed: the value it was +/// resumed with and how, unless it had not started. +pub(crate) struct Resumed { + generator: ObjId, + saved: SavedFrame, + received: Option<(Value, ResumeMode)>, +} + +impl Interp { + fn generator_state_mut(&mut self, g: ObjId) -> Option<&mut GenState> { + match self.heap.object_mut(g).map(|o| &mut o.class) { + Some(Class::Generator(s)) => Some(s), + _ => None, + } + } + + /// Marks the generator `g`, whose frame was popped without being saved, completed. + pub(crate) fn end_generator(&mut self, g: Option) { + if let Some(state) = g.and_then(|g| self.generator_state_mut(g)) + && let GenState::SuspendedStart(saved) | GenState::SuspendedYield(saved) = std::mem::replace(state, GenState::Completed) + { + self.release_saved(&saved); + } + } + + /// Takes a saved frame that left its generator object off the heap's total. + fn release_saved(&mut self, saved: &SavedFrame) { + self.heap.bytes = self.heap.bytes.saturating_sub(saved_bytes(saved)); + } + + /// Gives a frame's caller `v`: the Rust call that pushed a boundary frame, or the frame below. + fn deliver(&mut self, boundary: bool, v: Value) -> JsResult> { + if boundary { + return Ok(Some(v)); + } + self.push(v)?; + Ok(None) + } + + /// Moves `frame`, just popped, with its operands and `finally` entries, into a [`SavedFrame`]. + fn save_frame(&mut self, frame: Frame) -> SavedFrame { + let base = frame.base; + let stack = self.stack.split_off(base.min(self.stack.len())); + let i = self.finally_sites.partition_point(|&(_, slot)| slot < base); + let sites = self.finally_sites.split_off(i).into_iter().map(|(site, slot)| (site, slot - base)).collect(); + let mut marks = Vec::new(); + self.finally_marks.retain(|&(id, mark, slot)| { + let below = slot < base; + if !below { + marks.push((id, mark, slot - base)); + } + below + }); + SavedFrame { + code: frame.code, + pc: frame.pc, + env: frame.env, + var_env: frame.var_env, + env_depth: frame.env_depth, + this: frame.this, + callee: frame.callee, + completion: frame.completion, + stack, + sites, + marks, + } + } + + /// [`Op::GeneratorStart`](crate::bytecode::Op::GeneratorStart): OrdinaryCreateFromConstructor + /// of the function's `prototype` (section 14.4.11), or %GeneratorPrototype% when that is not an + /// object, holding the frame, which the call returns. + pub(crate) fn op_generator_start(&mut self) -> JsResult> { + let Some(callee) = self.frame()?.callee else { return internal("a generator's body without its function") }; + // A realm made without `Options::es2015` that reads the syntax later has no generator + // built-ins. + let Some(fallback) = self.symbols.objects.map(|o| o.generator_proto) else { + return Err(self.type_error("generators need the ECMAScript 2015 built-ins, and this realm was made without them")); + }; + let proto = match self.get_from(callee, &key("prototype"), &Value::Object(callee))? { + Value::Object(p) => p, + _ => fallback, + }; + self.rooted(&[Value::Object(proto)], |i| i.reserve_heap(OBJECT_BYTES + GENERATOR_BYTES))?; + let Some(frame) = self.frames.pop() else { return internal("no frame") }; + let boundary = frame.boundary; + let saved = self.save_frame(frame); + let bytes = saved_bytes(&saved); + let g = self.heap.alloc_object(Object::new(Class::Generator(Box::new(GenState::SuspendedStart(saved))), Some(proto))); + self.heap.bytes = self.heap.bytes.saturating_add(bytes); + self.deliver(boundary, Value::Object(g)) + } + + /// [`Op::Yield`](crate::bytecode::Op::Yield): GeneratorYield (section 25.4.3.7). The frame, + /// already past the instruction, goes into the generator object, and its caller gets the + /// iterator result. + pub(crate) fn op_yield(&mut self, raw: bool) -> JsResult> { + let Some(g) = self.frame()?.generator else { return internal("yield outside a generator's body") }; + if !raw { + let v = self.peek(0)?; + let result = iter_result(self, v, false)?; + self.replace(1, result)?; + } + let frame = self.frame()?; + let held = (self.stack.len().saturating_sub(frame.base)).saturating_add(self.finally_sites.len()).saturating_add(self.finally_marks.len()); + let bytes = GENERATOR_BYTES.saturating_add(SLOT_BYTES.saturating_mul(held)); + self.reserve_heap(bytes)?; + let result = self.pop()?; + let Some(frame) = self.frames.pop() else { return internal("no frame") }; + let boundary = frame.boundary; + let saved = self.save_frame(frame); + self.heap.bytes = self.heap.bytes.saturating_add(saved_bytes(&saved)); + let Some(state) = self.generator_state_mut(g) else { return internal("a generator's frame without its object") }; + *state = GenState::SuspendedYield(saved); + self.deliver(boundary, result) + } + + /// GeneratorResume and GeneratorResumeAbrupt (sections 25.4.3.3 and 25.4.3.4) for `next`, + /// `return` and `throw` called on `this` with `sent`: the result when the generator does not + /// run, or its frame to push. + pub(crate) fn prepare_resume(&mut self, this: Value, mode: ResumeMode, sent: Value) -> JsResult { + // Whether it has started, or `None` when it is running or completed. + let (g, started) = match this { + Value::Object(g) => match self.heap.object(g).map(|o| &o.class) { + Some(Class::Generator(s)) => match **s { + GenState::SuspendedStart(_) => (g, Some(false)), + GenState::SuspendedYield(_) => (g, Some(true)), + GenState::Executing => return Err(self.type_error("the generator is already running")), + GenState::Completed => (g, None), + }, + _ => return Err(self.type_error("the value is not a generator object")), + }, + _ => return Err(self.type_error("the value is not a generator object")), + }; + let Some(started) = started else { + return match mode { + ResumeMode::Next => Ok(Prepared::Done(iter_result(self, Value::Undefined, true)?)), + ResumeMode::Return => Ok(Prepared::Done(iter_result(self, sent, true)?)), + ResumeMode::Throw => Err(Abrupt::Throw(sent)), + }; + }; + if !started && mode != ResumeMode::Next { + self.end_generator(Some(g)); + return match mode { + ResumeMode::Throw => Err(Abrupt::Throw(sent)), + _ => Ok(Prepared::Done(iter_result(self, sent, true)?)), + }; + } + if self.frames.len() >= self.limits.frames { + return Err(Abrupt::Limit(LimitKind::Frames)); + } + let Some(state) = self.generator_state_mut(g) else { return internal("a generator object without its state") }; + let (GenState::SuspendedStart(saved) | GenState::SuspendedYield(saved)) = std::mem::replace(state, GenState::Executing) else { + return internal("a suspended generator without its frame"); + }; + self.release_saved(&saved); + let received = started.then_some((sent, mode)); + Ok(Prepared::Resume(Box::new(Resumed { generator: g, saved, received }))) + } + + /// Pushes a resumed generator's frame, with the value it was resumed with and how on top of + /// its operands when it had yielded. + pub(crate) fn enter_resumed(&mut self, r: Resumed, boundary: bool) -> JsResult<()> { + let Resumed { generator, saved, received } = r; + if self.frames.len() >= self.limits.frames { + let bytes = saved_bytes(&saved); + if let Some(state) = self.generator_state_mut(generator) { + *state = if received.is_some() { GenState::SuspendedYield(saved) } else { GenState::SuspendedStart(saved) }; + self.heap.bytes = self.heap.bytes.saturating_add(bytes); + } + return Err(Abrupt::Limit(LimitKind::Frames)); + } + let base = self.stack.len(); + self.drop_left_finally_sites(base); + let SavedFrame { code, pc, env, var_env, env_depth, this, callee, completion, stack, sites, marks } = saved; + self.stack.extend(stack); + if let Some((value, mode)) = received { + self.stack.push(value); + self.stack.push(Value::Number(mode.number())); + } + self.finally_sites.extend(sites.into_iter().map(|(site, slot)| (site, slot + base))); + self.finally_marks.extend(marks.into_iter().map(|(id, mark, slot)| (id, mark, slot + base))); + self.frames.push(Frame { + code, + pc, + base, + env, + var_env, + env_depth, + this, + callee, + construct: None, + completion, + boundary, + generator: Some(generator), + }); + Ok(()) + } + + /// [`Op::Resume`](crate::bytecode::Op::Resume): `received mode` → `received`. + pub(crate) fn op_resume(&mut self, target: u32) -> JsResult<()> { + let mode = ResumeMode::of(&self.peek(0)?)?; + let received = self.peek(1)?; + self.pop()?; + self.pop()?; + match mode { + ResumeMode::Next => self.push(received), + ResumeMode::Throw => { + self.thrown_mark = None; + Err(Abrupt::Throw(received)) + } + ResumeMode::Return => { + self.push(received)?; + self.jump_to(target) + } + } + } + + /// GetMethod (section 7.3.10): the property `name` of `v`, `None` when it is `undefined` or + /// `null`. + fn get_method(&mut self, v: &Value, name: &str) -> JsResult> { + let f = self.get_value(v, &key(name))?; + if f.is_nullish() { + return Ok(None); + } + if !self.is_callable(&f) { + return Err(self.type_error(&format!("the iterator's {name} is not a function"))); + } + Ok(Some(f)) + } + + /// [`Op::GetIterator`](crate::bytecode::Op::GetIterator): `value` → `iterator next`. + pub(crate) fn op_get_iterator(&mut self) -> JsResult<()> { + let v = self.peek(0)?; + let Some(sym) = self.well_known(|w| &w.iterator) else { return internal("no Symbol.iterator in this realm") }; + let method = self.get_value_sym(&v, &sym)?; + if !self.is_callable(&method) { + return Err(self.type_error("the value is not iterable")); + } + let iterator = self.call(&method, &v, &[])?; + if !matches!(iterator, Value::Object(_)) { + return Err(self.type_error("the iterator is not an object")); + } + self.replace(1, iterator.clone())?; + let next = self.get_value(&iterator, &key("next"))?; + self.push(next) + } + + /// [`Op::DelegateCall`](crate::bytecode::Op::DelegateCall): the method of `yield*`'s iterator + /// that the generator's resumption calls (section 14.4.14, step 7). + pub(crate) fn op_delegate_call(&mut self, target: u32) -> JsResult<()> { + let mode = ResumeMode::of(&self.peek(0)?)?; + let iterator = self.peek(3)?; + let method = match mode { + ResumeMode::Next => Some(self.peek(2)?), + ResumeMode::Throw => self.get_method(&iterator, "throw")?, + ResumeMode::Return => self.get_method(&iterator, "return")?, + }; + let received = self.peek(1)?; + match (method, mode) { + (Some(m), _) => { + self.replace(2, Value::Number(mode.number()))?; + self.push(m)?; + self.push(iterator)?; + self.push(received) + } + (None, ResumeMode::Return) => { + self.replace(2, received)?; + self.jump_to(target) + } + (None, _) => { + // The iterator has no `throw`: it is closed, and the protocol violation is a + // `TypeError` (step 7.b.iii). + if let Some(close) = self.get_method(&iterator, "return")? { + let result = self.call(&close, &iterator, &[])?; + if !matches!(result, Value::Object(_)) { + return Err(self.type_error("the iterator result is not an object")); + } + } + Err(self.type_error("the iterator has no throw method")) + } + } + } + + /// [`Op::DelegateResult`](crate::bytecode::Op::DelegateResult): `mode result` → `result`, or + /// when it is done, a jump with `mode value`. + pub(crate) fn op_delegate_result(&mut self, target: u32) -> JsResult<()> { + let result = self.peek(0)?; + if !matches!(result, Value::Object(_)) { + return Err(self.type_error("the iterator result is not an object")); + } + if self.get_value(&result, &key("done"))?.truthy() { + let value = self.get_value(&result, &key("value"))?; + self.replace(1, value)?; + return self.jump_to(target); + } + self.replace(2, result) + } + + /// [`Op::DelegateDone`](crate::bytecode::Op::DelegateDone): `mode value` → `value`, a jump for + /// `return`. + pub(crate) fn op_delegate_done(&mut self, target: u32) -> JsResult<()> { + let mode = ResumeMode::of(&self.peek(1)?)?; + let value = self.peek(0)?; + self.replace(2, value)?; + if mode == ResumeMode::Return { + return self.jump_to(target); + } + Ok(()) + } +} diff --git a/crates/js/src/generator_tests.rs b/crates/js/src/generator_tests.rs new file mode 100644 index 0000000000..fcdd00033e --- /dev/null +++ b/crates/js/src/generator_tests.rs @@ -0,0 +1,305 @@ +//! Generator functions, `yield`, `yield*` and the generator objects, in a realm with +//! [`Options::es2015`]. + +use crate::{JsValue, LimitKind, Limits, Options, Realm, RunError, RunErrorKind}; + +fn es2015(limits: Limits) -> Realm { + Realm::with_options(Options { es2015: true, ..Options::default() }, limits) +} + +fn run(src: &str) -> JsValue { + match es2015(Limits::default()).run(src) { + Ok(v) => v, + Err(e) => panic!("{src}\n{e:?}"), + } +} + +fn truth(src: &str) { + assert_eq!(run(src), JsValue::Bool(true), "{src}"); +} + +fn string(src: &str) -> String { + match run(src) { + JsValue::String(s) => s, + other => panic!("{src}: {other:?}"), + } +} + +/// The run throws an error whose message starts with `name`. +fn throws(src: &str, name: &str) { + match es2015(Limits::default()).run(src) { + Err(RunError { kind: RunErrorKind::Thrown, message, .. }) => assert!(message.starts_with(name), "{src}: {message}"), + other => panic!("{src}: {other:?}"), + } +} + +/// The script does not parse in a realm with `options`. +fn syntax_with(src: &str, options: Options) { + match Realm::with_options(options, Limits::default()).run(src) { + Err(RunError { kind: RunErrorKind::Syntax, .. }) => {} + other => panic!("{src}: {other:?}"), + } +} + +fn syntax(src: &str) { + syntax_with(src, Options { es2015: true, ..Options::default() }); +} + +#[test] +fn a_generator_runs_its_body_one_yield_at_a_time() { + assert_eq!( + string( + "var log = []; function* g(a, b) { log.push('start'); var x = yield a; log.push(x); yield b + x; return 'end'; } \ + var it = g(1, 2); log.push('made'); var r = [it.next('ignored'), it.next(10), it.next(20), it.next()]; \ + log.join() + ' ' + r.map(function (o) { return o.value + ':' + o.done; }).join()" + ), + "made,start,10 1:false,12:false,end:true,undefined:true" + ); + // The parameters' default values run at the call, the body at the first `next`. + assert_eq!(string("var log = []; function* g(a = log.push('d')) { log.push('b'); } var it = g(); log.push('c'); it.next(); log.join()"), "d,c,b"); + truth("function* g() { yield this; } var o = { g: g }; o.g().next().value === o"); + truth("function* g() { return arguments.length; } g(1, 2, 3).next().value === 3"); + truth("var it = (function* () {})(); var r = it.next(); r.value === undefined && r.done === true"); + truth("function* g() { yield 1; } var a = g(), b = g(); a.next(); a.next().done && !b.next().done"); +} + +#[test] +fn yield_takes_an_operand_only_on_the_same_line() { + assert_eq!(string("function* g() { yield\n1; } var it = g(); String(it.next().value) + ',' + it.next().done"), "undefined,true"); + truth("function* g() { var x = yield; return x; } var it = g(); it.next(); it.next(7).value === 7"); + truth("function* g() { yield /a/g; } g().next().value instanceof RegExp"); + truth("function* g() { yield yield 1; } var it = g(); it.next().value === 1 && it.next(2).value === 2"); + truth("function* g() { var a = [yield 1, yield 2]; return a.join(); } var it = g(); it.next(); it.next('x'); it.next('y').value === 'x,y'"); +} + +#[test] +fn return_runs_the_finally_blocks_around_the_yield() { + truth( + "var log = []; function* g() { try { yield 1; yield 2; } finally { log.push('f'); } } \ + var it = g(); it.next(); var r = it.return(9); r.value === 9 && r.done === true && log.join() === 'f' && it.next().done", + ); + // A `finally` block that yields suspends the return, which ends at the next resumption. + assert_eq!( + string( + "function* g() { try { yield 1; } finally { yield 'cleanup'; } } var it = g(); it.next(); \ + var a = it.return(5), b = it.next(), c = it.next(); [a.value, a.done, b.value, b.done, c.done].join()" + ), + "cleanup,false,5,true,true" + ); + truth("function* g() { try { yield 1; } finally { return 'override'; } } var it = g(); it.next(); it.return(5).value === 'override'"); + // Before the body starts, and after it ends, `return` only completes the generator. + truth("var ran = false; function* g() { ran = true; } var it = g(); var r = it.return(3); r.value === 3 && r.done && !ran && it.next().done"); + truth("function* g() {} var it = g(); it.next(); var r = it.return(4); r.value === 4 && r.done"); +} + +#[test] +fn throw_goes_into_a_suspended_generator() { + truth("function* g() { try { yield 1; } catch (e) { yield 'caught ' + e; } } var it = g(); it.next(); it.throw('x').value === 'caught x'"); + truth( + "function* g() { yield 1; yield 2; } var it = g(); it.next(); var e; try { it.throw(new RangeError('r')); } catch (x) { e = x; } \ + e instanceof RangeError && it.next().done", + ); + // A generator that has not started is completed by `throw`, which its body never sees. + truth("var ran = false; function* g() { ran = true; } var it = g(); try { it.throw(1); } catch (e) {} !ran && it.next().done"); + throws("function* g() {} var it = g(); it.next(); it.throw(new TypeError('after the end'));", "TypeError: after the end"); +} + +#[test] +fn resuming_a_running_generator_is_a_type_error() { + truth( + "var it; function* g() { try { it.next(); } catch (e) { yield e instanceof TypeError; } } it = g(); \ + it.next().value === true", + ); + truth("var it; function* g() { it.next(); } it = g(); var e; try { it.next(); } catch (x) { e = x; } e instanceof TypeError && it.next().done"); + throws("var g = function* () {}; g.prototype.next.call({});", "TypeError"); + throws("(function* () {}).prototype.next.call(1);", "TypeError"); +} + +#[test] +fn yield_star_delegates_next_throw_and_return() { + truth( + "function* g() { yield* [1, 2]; yield* 'ab'; } var r = []; var it = g(), s; while (!(s = it.next()).done) r.push(s.value); r.join() === '1,2,a,b'", + ); + truth( + "function* inner() { yield 1; return 'r'; } function* outer() { var v = yield* inner(); yield v; } var it = outer(); it.next().value === 1 && it.next().value === 'r'", + ); + // The values `next` sends go to the delegate. + truth( + "function* inner() { var x = yield 1; yield x * 2; } function* outer() { yield* inner(); } var it = outer(); it.next(); it.next(21).value === 42", + ); + truth( + "var log = []; function* inner() { try { yield 1; } finally { log.push('inner'); } } function* outer() { try { yield* inner(); } finally { log.push('outer'); } } \ + var it = outer(); it.next(); var r = it.return(7); r.value === 7 && r.done && log.join() === 'inner,outer'", + ); + truth( + "function* inner() { try { yield 1; } catch (e) { yield 'in ' + e; } } function* outer() { yield* inner(); } var it = outer(); it.next(); it.throw('t').value === 'in t'", + ); + // The delegate's own results are passed on as they are. + truth( + "var r = { done: false, value: 1, extra: 2 }; var o = {}; o[Symbol.iterator] = function () { return { next: function () { return r; } }; }; function* g() { yield* o; } g().next() === r", + ); + // A delegate without `throw` is closed, and the generator gets a TypeError. + truth( + "var closed = false; var o = {}; o[Symbol.iterator] = function () { return { next: function () { return { done: false }; }, return: function () { closed = true; return {}; } }; }; \ + function* g() { yield* o; } var it = g(); it.next(); var e; try { it.throw(1); } catch (x) { e = x; } e instanceof TypeError && closed", + ); + throws("function* g() { yield* 5; } g().next();", "TypeError"); + throws( + "var o = {}; o[Symbol.iterator] = function () { return { next: function () { return 1; } }; }; function* g() { yield* o; } g().next();", + "TypeError", + ); +} + +#[test] +fn generator_methods_and_the_generator_objects() { + truth("var o = { *g(a) { yield this === o && a; } }; o.g(5).next().value === 5"); + truth("var o = { *'s'() { yield 1; }, *2() { yield 2; } }; o.s().next().value + o[2]().next().value === 3"); + throws("function* g() {} new g();", "TypeError"); + throws("var o = { *m() {} }; new o.m();", "TypeError"); + truth("function* g() {} var GP = Object.getPrototypeOf(g); GP === Object.getPrototypeOf(function* () {}) && GP !== Function.prototype"); + truth("function* g() {} Object.getPrototypeOf(g.prototype) === Object.getPrototypeOf(g).prototype && !g.prototype.hasOwnProperty('constructor')"); + truth("function* g() {} var it = g(); it[Symbol.iterator]() === it && Object.prototype.toString.call(it) === '[object Generator]'"); + truth("function* g() {} Object.prototype.toString.call(g) === '[object GeneratorFunction]' && g instanceof Function && typeof g === 'function'"); + // %GeneratorFunction.prototype% is an ordinary object, not a function (section 25.2.3). + truth("var GP = Object.getPrototypeOf(function* () {}); typeof GP === 'object' && Object.getPrototypeOf(GP) === Function.prototype"); + throws("Object.getPrototypeOf(function* () {})();", "TypeError"); + truth( + "var GF = Object.getPrototypeOf(function* () {}).constructor; var f = GF('a', 'yield a; yield a * 2;'); var it = f(3); it.next().value + it.next().value === 9", + ); + truth( + "var GF = Object.getPrototypeOf(function* () {}).constructor; Object.getPrototypeOf(GF) === Function && GF.prototype === Object.getPrototypeOf(function* () {})", + ); + truth( + "var GF = Object.getPrototypeOf(function* () {}).constructor; typeof this.GeneratorFunction === 'undefined' && new GF('yield 1')().next().value === 1", + ); + truth("function* g() { yield 1 } String(g) === 'function* g() { yield 1 }'"); + // A generator function's own `prototype` is used when it is an object. + truth("function* g() {} var p = { mark: 1 }; g.prototype = p; Object.getPrototypeOf(g()) === p"); + truth("function* g() {} g.prototype = 1; Object.getPrototypeOf(g()) === Object.getPrototypeOf(function* () {}).prototype"); +} + +#[test] +fn yield_is_an_identifier_outside_generators_in_sloppy_code() { + truth("var yield = 1; yield + 1 === 2"); + truth("function f(yield) { return yield; } f(3) === 3"); + truth("function* g() { function f() { var yield = 4; return yield; } yield f(); } g().next().value === 4"); + truth("function* g() { var o = { yield: 5 }; yield o.yield; } g().next().value === 5"); + truth("function* yield() { yield 6; } yield().next().value === 6"); + syntax("'use strict'; var yield = 1;"); +} + +#[test] +fn bad_generators_are_syntax_errors() { + for src in [ + "function* g() { var yield; }", + "function* g(yield) {}", + "function* g(a = yield) {}", + "function* g() { function* h(a = yield 1) {} }", + "var f = function* yield() {};", + "function* g() { (yield) => 1; }", + "function* g() { yield = 1; }", + "function* g() { yi\\u0065ld 1; }", + "function* g() { yield\n* 1; }", + "function* g() { yield: 1; }", + "if (true) function* g() {}", + "L: function* g() {}", + "{ function* g() {} function* g() {} }", + "function* g() { yield* ; }", + "var o = { *m(a, a) {} };", + "function* g() { (a = yield) => 1; }", + ] { + syntax(src); + } + // A `yield` in the body of a function in a generator's parameters belongs to that function. + truth("function* g(a = function* () { yield 1; }) { yield* a(); } g().next().value === 1"); + truth("function* g(a = function* () { yield 2; }, b = (c = function* () { yield 3; }) => c) { yield* b()(); } g().next().value === 3"); +} + +#[test] +fn realms_without_es2015_have_no_generators() { + let es5 = Options::default(); + let extendscript = Options { e4x: true, preprocessor_lines: true, ..Options::default() }; + for options in [es5, extendscript] { + for src in ["function* g() {}", "var g = function* () {};", "var o = { *m() {} };"] { + syntax_with(src, options.clone()); + } + let mut realm = Realm::with_options(options, Limits::default()); + assert_eq!(realm.run("function f() { var yield = 2; return yield; } f()"), Ok(JsValue::Number(2.0))); + // Reading the syntax later does not add the built-ins, so a call is a TypeError. + realm.set_es2015(true); + match realm.run("function* g() { yield 1; } g();") { + Err(RunError { kind: RunErrorKind::Thrown, message, .. }) => assert!(message.starts_with("TypeError"), "{message}"), + other => panic!("{other:?}"), + } + } +} + +#[test] +fn a_suspended_generator_keeps_its_frame_across_a_collection() { + let mut realm = es2015(Limits::default()); + let setup = "function* g() { var local = { v: 'left' }; var r = [{ w: 'held' }, yield 1]; yield local.v + r[0].w + r[1]; } \ + var it = g(); it.next(); it.next('!').value"; + assert_eq!(realm.run(setup), Ok(JsValue::String("leftheld!".into()))); + // The operands on the stack at the `yield` (the array being built) survive a collection. + assert_eq!(realm.run("var it3 = g(); it3.next(); 'ok'"), Ok(JsValue::String("ok".into()))); + realm.collect_garbage(); + assert_eq!(realm.run("it3.next('#').value"), Ok(JsValue::String("leftheld#".into()))); +} + +#[test] +fn a_frame_taken_out_of_its_generator_leaves_the_heap_total() { + let mut realm = es2015(Limits::default()); + // At the `yield`, the 500 arguments before it are operands in the saved frame. + let args = vec!["0"; 500].join(", "); + let setup = format!("function f() {{}} function* g() {{ while (true) f({args}, yield 1); }} var it = g(); it.next(); 0"); + assert_eq!(realm.run(&setup), Ok(JsValue::Number(0.0))); + let mut gaps = Vec::new(); + for resumes in [10, 210] { + realm.collect_garbage(); + assert_eq!(realm.run(&format!("for (var i = 0; i < {resumes}; i++) it.next(); 0")), Ok(JsValue::Number(0.0))); + let counted = realm.interp().heap.bytes; + gaps.push(counted.saturating_sub(realm.collect_garbage())); + } + // 200 more resumptions leave far less than one saved frame's worth each. + assert!(gaps[1] < gaps[0] + 200 * 1024, "{gaps:?}"); +} + +#[test] +fn an_unreachable_suspended_generator_is_freed() { + let mut realm = es2015(Limits::default()); + let setup = "function* g() { var big = []; for (var i = 0; i < 20000; i++) big.push({ i: i }); yield big.length; } var it = g(); it.next().value"; + assert_eq!(realm.run(setup), Ok(JsValue::Number(20000.0))); + let held = realm.collect_garbage(); + assert_eq!(realm.run("it = null; 0"), Ok(JsValue::Number(0.0))); + let freed = realm.collect_garbage(); + assert!(freed + 1_000_000 < held, "held {held}, after {freed}"); +} + +#[test] +fn generators_stay_within_the_limits() { + let mut realm = es2015(Limits { fuel: 20_000, ..Limits::default() }); + match realm.run("function* g() { while (true) yield 1; } var it = g(); while (true) it.next();") { + Err(RunError { kind: RunErrorKind::Limit(LimitKind::Fuel), .. }) => {} + other => panic!("{other:?}"), + } + // Each resumption takes fuel even when the body does no work. + let mut realm = es2015(Limits { fuel: 20_000, ..Limits::default() }); + match realm.run("var it = (function* () {})(); it.next(); while (true) it.next();") { + Err(RunError { kind: RunErrorKind::Limit(LimitKind::Fuel), .. }) => {} + other => panic!("{other:?}"), + } + // A deep `yield*` chain stops at the frame limit, and the realm can run again. + let mut realm = es2015(Limits { frames: 200, ..Limits::default() }); + match realm.run("function* d(n) { if (n) yield* d(n - 1); else yield 1; } d(1000).next();") { + Err(RunError { kind: RunErrorKind::Limit(LimitKind::Frames), .. }) => {} + other => panic!("{other:?}"), + } + assert_eq!(realm.run("function* d(n) { if (n) yield* d(n - 1); else yield 1; } d(20).next().value"), Ok(JsValue::Number(1.0))); + // A generator whose body was running when a limit ended the run cannot be resumed. + let mut realm = es2015(Limits { fuel: 20_000, ..Limits::default() }); + match realm.run("var it = (function* () { while (true) {} })(); it.next();") { + Err(RunError { kind: RunErrorKind::Limit(LimitKind::Fuel), .. }) => {} + other => panic!("{other:?}"), + } + assert_eq!(realm.run("var r = it.next(); r.done && r.value === undefined"), Ok(JsValue::Bool(true))); +} diff --git a/crates/js/src/heap.rs b/crates/js/src/heap.rs index d40e75609b..d5e21359ba 100644 --- a/crates/js/src/heap.rs +++ b/crates/js/src/heap.rs @@ -171,6 +171,8 @@ pub(crate) enum NativeKind { Apply, /// The global `eval`: a call to it by that name is a direct eval. Eval, + /// `%GeneratorPrototype%`'s `next`, `return` or `throw`. + Resume(crate::generator::ResumeMode), } /// What a function object runs. `Bound` is a function made by `Function.prototype.bind` (section @@ -231,6 +233,8 @@ pub(crate) enum Class { Symbol(crate::symbol::Sym), /// An Array Iterator or a String Iterator and how far it has gone (sections 22.1.5 and 21.1.5). Iterator(Box), + /// A generator object and its state (ECMA-262 11th edition, section 25.4). + Generator(Box), ForIn(Box), /// The `Math` object (section 15.8). Math, @@ -316,7 +320,7 @@ impl Class { Class::XmlFilter(_) => "Object", Class::Math => "Math", Class::Json => "JSON", - Class::Ordinary | Class::ForIn(_) | Class::Symbol(_) | Class::Iterator(_) => "Object", + Class::Ordinary | Class::ForIn(_) | Class::Symbol(_) | Class::Iterator(_) | Class::Generator(_) => "Object", Class::Array { .. } => "Array", Class::Function(_) => "Function", Class::Error(_) => "Error", @@ -717,6 +721,24 @@ fn trace_object(o: &Object, work: &mut Vec, strings: &mut StringSizes) -> u crate::builtins::iterator::IterState::Array { target, .. } => work.extend(target.iter().map(|o| o.0)), crate::builtins::iterator::IterState::String { text, .. } => text.iter().for_each(|s| strings.add(s)), }, + Class::Generator(state) => { + if let Some(saved) = state.saved() { + work.push(saved.env.0); + work.push(saved.var_env.0); + work.extend(saved.callee.iter().map(|o| o.0)); + work.extend(saved.marks.iter().map(|&(id, _, _)| id.0)); + mark_value(&saved.this, work, strings); + mark_value(&saved.completion, work, strings); + for v in &saved.stack { + mark_value(v, work, strings); + } + mark_code(&saved.code, strings); + for ((code, _), _) in &saved.sites { + mark_code(code, strings); + } + extra = crate::generator::saved_bytes(saved); + } + } Class::Xml(node) => { work.extend(node.parent.iter().chain(&node.attrs).chain(&node.children).map(|o| o.0)); strings.add(&node.value); diff --git a/crates/js/src/interp.rs b/crates/js/src/interp.rs index b05953b36c..acf645bbde 100644 --- a/crates/js/src/interp.rs +++ b/crates/js/src/interp.rs @@ -4,7 +4,9 @@ //! JavaScript recursion uses the heap, not the Rust stack. The loop runs again inside a Rust call //! only where the language needs a function's result in the middle of an operation (a getter or //! setter, `valueOf` and `toString` during a conversion, indirect `eval`); those nested runs are -//! counted against [`crate::Limits::reentry`]. +//! counted against [`crate::Limits::reentry`]. A generator's body runs in a frame of its own, +//! which `yield` moves into the generator object, operands included, and a call to its `next`, +//! `return` or `throw` pushes again ([`crate::generator`]). //! //! Before each instruction the interpreter takes one unit of fuel, checks the interrupt flag and, //! when the heap has grown past its threshold, collects garbage. Running out of fuel, the heap @@ -49,7 +51,7 @@ pub(crate) type JsResult = Result; /// with a NUL, which no identifier holds. const ARROW_THIS: &[u16] = &[0, 0x74, 0x68, 0x69, 0x73]; -fn internal(message: &str) -> JsResult { +pub(crate) fn internal(message: &str) -> JsResult { Err(Abrupt::Internal(message.into())) } @@ -173,22 +175,24 @@ pub(crate) struct Frame { pub(crate) code: Rc, pub(crate) pc: usize, /// Where this frame's operands start on the operand stack. - base: usize, + pub(crate) base: usize, pub(crate) env: EnvId, pub(crate) var_env: EnvId, /// `with` and catch environments entered and not yet left. - env_depth: u32, - this: Value, - callee: Option, + pub(crate) env_depth: u32, + pub(crate) this: Value, + pub(crate) callee: Option, /// The object `new` made, returned unless the function returns an object. - construct: Option, - completion: Value, + pub(crate) construct: Option, + pub(crate) completion: Value, /// Returning from this frame returns from the Rust call that pushed it. - boundary: bool, + pub(crate) boundary: bool, + /// The generator object whose body this frame runs, once [`Op::GeneratorStart`] has made it. + pub(crate) generator: Option, } /// Where the exception being thrown was raised: the code and the instruction. -type ThrowSite = (Rc, usize); +pub(crate) type ThrowSite = (Rc, usize); /// What [`crate::Realm::observe_code`] calls with each source evaluated at run time. pub(crate) type CodeObserver = Rc; @@ -450,7 +454,7 @@ fn declaration_bytes(code: &Code) -> usize { } /// A call to a function written in JavaScript, ready to enter. -struct Entry { +pub(crate) struct Entry { callee: ObjId, code: Rc, env: EnvId, @@ -459,9 +463,11 @@ struct Entry { } /// What a call resolved to. -enum Prepared { +pub(crate) enum Prepared { Closure(Entry), Done(Value), + /// A generator's `next`, `return` or `throw` that goes on with its body. + Resume(Box), } /// A variable found in the environment chain. @@ -762,7 +768,7 @@ impl Interp { /// Removes the [`Self::finally_sites`] entries whose stack slot is at or above `len`: those of /// `finally` blocks that were left. The slots rise along the list, so only its end is looked at. - fn drop_left_finally_sites(&mut self, len: usize) { + pub(crate) fn drop_left_finally_sites(&mut self, len: usize) { while let Some(&(_, slot)) = self.finally_sites.last() { #[cfg(test)] SITE_CHECKS.with(|c| c.set(c.get() + 1)); @@ -788,7 +794,7 @@ impl Interp { for f in &self.frames { roots.values.push(&f.this); roots.values.push(&f.completion); - roots.objects.extend(f.callee.iter().chain(f.construct.iter())); + roots.objects.extend(f.callee.iter().chain(f.construct.iter()).chain(f.generator.iter())); roots.envs.push(f.env); roots.envs.push(f.var_env); roots.codes.push(&f.code); @@ -872,6 +878,8 @@ impl Interp { let v = self.frame()?.completion.clone(); self.return_value(v) } + Op::GeneratorStart => self.op_generator_start(), + Op::Yield(raw) => self.op_yield(raw), _ => self.exec(op).map(|()| None), } } @@ -926,6 +934,7 @@ impl Interp { } let Some(frame) = self.frames.pop() else { return Err(Abrupt::Throw(v)) }; self.stack.truncate(frame.base); + self.end_generator(frame.generator); if frame.boundary { self.passing = v.clone(); return Err(Abrupt::Throw(v)); @@ -942,6 +951,7 @@ impl Interp { fn abort_to_boundary(&mut self) { while let Some(frame) = self.frames.pop() { self.stack.truncate(frame.base); + self.end_generator(frame.generator); if frame.boundary { break; } @@ -949,8 +959,15 @@ impl Interp { } fn return_value(&mut self, v: Value) -> JsResult> { + // A generator's body that returns ends it, and its caller gets `{ value, done: true }`, + // made while the frame is still there to fail in. + let v = match self.frames.last().and_then(|f| f.generator) { + Some(_) => crate::builtins::iterator::iter_result(self, v, true)?, + None => v, + }; let Some(frame) = self.frames.pop() else { return internal("return without a frame") }; self.stack.truncate(frame.base); + self.end_generator(frame.generator); // A `return` in a finally block leaves the block, and the value takes its exception's slot. self.drop_left_finally_sites(frame.base); let v = match frame.construct { @@ -1102,7 +1119,12 @@ impl Interp { self.replace(1, Value::String(s)) } Op::TemplateObject(i) => self.op_template_object(i), - Op::Return | Op::ReturnCompletion => internal("return reached the dispatcher"), + Op::Resume(t) => self.op_resume(t), + Op::GetIterator => self.op_get_iterator(), + Op::DelegateCall(t) => self.op_delegate_call(t), + Op::DelegateResult(t) => self.op_delegate_result(t), + Op::DelegateDone(t) => self.op_delegate_done(t), + Op::Return | Op::ReturnCompletion | Op::GeneratorStart | Op::Yield(_) => internal("a frame-ending instruction reached the dispatcher"), } } @@ -2103,7 +2125,8 @@ impl Interp { Some(_) => self.heap.alloc_env(Env::Decl { bindings: PropMap::default(), outer: Some(env) }), None => env, }; - let proto = self.intrinsics.function_proto; + let generator = code.generator.then(|| self.symbols.objects.map(|o| (o.generator_function_proto, o.generator_proto))).flatten(); + let proto = generator.map_or(self.intrinsics.function_proto, |(function_proto, _)| function_proto); let length = code.length; let strict = code.strict; let arrow = code.arrow; @@ -2114,6 +2137,17 @@ impl Interp { if arrow { return Ok(f); } + // A generator function's `prototype` inherits from %GeneratorPrototype% and has no + // `constructor` (ECMA-262 11th edition, section 14.4.13). A generator function has no own + // `caller` or `arguments`, strict or not (section 16.2). + if let Some((_, generator_proto)) = generator { + let p = self.heap.alloc_object(Object::new(Class::Ordinary, Some(generator_proto))); + self.define(f, key("prototype"), Prop::Data { value: Value::Object(p), flags: WRITABLE })?; + if let Some(name) = self_name { + self.env_insert(env, name, Binding::new(Value::Object(f), false, false))?; + } + return Ok(f); + } let p = self.new_object(); self.define(p, key("constructor"), Prop::Data { value: Value::Object(f), flags: HIDDEN })?; self.define(f, key("prototype"), Prop::Data { value: Value::Object(p), flags: WRITABLE })?; @@ -2567,6 +2601,11 @@ impl Interp { let callee = f.as_object().ok_or_else(|| Abrupt::Internal("callee is not an object".into()))?; return Ok(Prepared::Closure(Entry { callee, code, env, this, args })); } + Func::Native { kind: NativeKind::Resume(mode), .. } => { + self.use_fuel()?; + let sent = args.into_iter().next().unwrap_or(Value::Undefined); + return self.prepare_resume(this, mode, sent); + } Func::Native { kind: NativeKind::Call, .. } => { self.use_fuel()?; f = this; @@ -2689,6 +2728,10 @@ impl Interp { self.stack.truncate(start); self.enter_function(entry, None, false) } + Prepared::Resume(r) => { + self.stack.truncate(start); + self.enter_resumed(*r, false) + } } } @@ -2709,6 +2752,7 @@ impl Interp { } match self.func_of(&f) { Some(Func::Closure { code, .. }) if code.arrow => Err(self.type_error("an arrow function is not a constructor")), + Some(Func::Closure { code, .. }) if code.generator => Err(self.type_error("a generator function is not a constructor")), Some(Func::Closure { code, env }) => { let Some(callee) = f.as_object() else { return internal("callee is not an object") }; let proto = match self.get_from(callee, &key("prototype"), &f)? { @@ -2785,6 +2829,7 @@ impl Interp { construct, completion: Value::Undefined, boundary, + generator: None, }); Ok(()) } @@ -3009,6 +3054,11 @@ impl Interp { self.enter_function(entry, None, true)?; self.execute() } + Prepared::Resume(r) => { + self.stack.truncate(saved); + self.enter_resumed(*r, true)?; + self.execute() + } } } @@ -3207,6 +3257,7 @@ impl Interp { construct: None, completion: Value::Undefined, boundary, + generator: None, }); Ok(()) } diff --git a/crates/js/src/interp_tests.rs b/crates/js/src/interp_tests.rs index d0bed32c1d..1f17b90055 100644 --- a/crates/js/src/interp_tests.rs +++ b/crates/js/src/interp_tests.rs @@ -983,6 +983,7 @@ fn code(ops: Vec) -> Code { arrow: false, uses_this: false, param_init: false, + generator: false, } } diff --git a/crates/js/src/lib.rs b/crates/js/src/lib.rs index 7804a5858d..44b6d4e92f 100644 --- a/crates/js/src/lib.rs +++ b/crates/js/src/lib.rs @@ -54,8 +54,17 @@ //! functions (section 14.2), template literals and tagged templates (sections 12.2.9 and //! 12.3.7), default and rest parameters (section 14.1) and spread in array literals, calls and //! `new` (sections 12.2.5 and 12.3.6.1). Spread reads arrays, strings (by code point) and objects -//! with a `length`, by index; other values are a `TypeError`. Destructuring, `for … of`, classes, -//! generators and modules stay syntax errors. +//! with a `length`, by index; other values are a `TypeError`. Destructuring, `for … of`, classes +//! and modules stay syntax errors. +//! +//! With [`Options::es2015`], the parser and the realm also have generators (ECMA-262 11th edition, +//! sections 14.4 and 25.4): `function*` declarations and expressions, `*name() {…}` methods in +//! object literals, `yield` and `yield*`, which passes `next`, `throw` and `return` on to the +//! iterator it delegates to, and generator objects with `next`, `return` and `throw` from +//! `%GeneratorPrototype%`, reached through `%GeneratorFunction%`. Outside a generator function's +//! body and parameters, `yield` stays an identifier in sloppy code. A generator's suspended frame +//! lives in the heap, each resumption takes fuel and counts against the frame limit, and resuming a +//! generator while its body runs is a `TypeError`. //! //! With [`Options::es2015`], the realm also has `Symbol` (ECMA-262 11th edition, section 19.4, //! ): `Symbol.for` and `Symbol.keyFor` over a registry @@ -80,6 +89,7 @@ mod compiler; mod date_builtins; mod error; mod file_classes; +mod generator; mod heap; mod host; mod interp; @@ -241,6 +251,8 @@ mod es2015_tests; #[cfg(test)] mod extension_tests; #[cfg(test)] +mod generator_tests; +#[cfg(test)] mod host_tests; #[cfg(test)] mod interp_tests; diff --git a/crates/js/src/parser.rs b/crates/js/src/parser.rs index db034d1e2d..b90d9e3a66 100644 --- a/crates/js/src/parser.rs +++ b/crates/js/src/parser.rs @@ -36,6 +36,9 @@ struct Context { breakables: u32, /// The current function body's directive prologue has a `"use strict"` directive. use_strict: bool, + /// The code is a generator function's body or parameters: `yield` starts a yield expression + /// there and is not an identifier (ECMA-262 2015 sections 12.1.1 and 14.4). + generator: bool, } /// The names declared in a scope, for the early errors of ECMA-262 2015 about redeclarations @@ -101,6 +104,9 @@ pub(crate) struct Parser<'s> { es2015: bool, /// The scopes open around the current token, outermost first (only with `es2015`). scopes: Vec, + /// Where each yield expression read so far starts, in the order read, so the parameters of a + /// generator function and an arrow function's head can be checked for one. + yields: Vec, } impl<'s> Parser<'s> { @@ -125,6 +131,7 @@ impl<'s> Parser<'s> { e4x: options.e4x, es2015: options.es2015, scopes: if options.es2015 { vec![Scope { function: true, ..Scope::default() }] } else { Vec::new() }, + yields: Vec::new(), }; parser.tok = parser.next_significant()?; Ok(parser) @@ -266,9 +273,18 @@ impl<'s> Parser<'s> { if self.ctx.strict && strict_reserved(name) { return Err(self.error_at_token(token, format!("'{name}' is a reserved word in strict mode"))); } + if self.ctx.generator && name == "yield" { + return Err(self.error_at_token(token, "'yield' cannot be an identifier in a generator function")); + } Ok(()) } + /// A yield expression starts at `offset` or later, before `end`. + fn yield_between(&self, offset: u32, end: u32) -> bool { + let i = self.yields.partition_point(|&y| y < offset); + self.yields.get(i).is_some_and(|&y| y < end) + } + /// Reads an identifier that a declaration binds: checked as [`Self::check_identifier`] does, /// and in strict code neither `eval` nor `arguments`. fn binding_identifier(&mut self) -> Result { @@ -341,7 +357,7 @@ impl<'s> Parser<'s> { /// Declares a function declaration that stands in a statement list: var-scoped in a function /// body or the script, lexical in a block. fn declare_function(&mut self, id: crate::ast::FunctionId) -> Result<()> { - let Some(name) = self.ast.function(id).and_then(|f| f.name.clone()) else { return Ok(()) }; + let Some((name, generator)) = self.ast.function(id).and_then(|f| Some((f.name.clone()?, f.generator))) else { return Ok(()) }; match self.scopes.last_mut() { Some(scope) if scope.function => { if scope.lexical.contains_key(&name.name) { @@ -350,7 +366,8 @@ impl<'s> Parser<'s> { scope.vars.insert(name.name); Ok(()) } - Some(_) => self.declare_lexical(&name, true), + // Only plain function declarations may repeat in a block (Annex B.3.3.4). + Some(_) => self.declare_lexical(&name, !generator), None => Ok(()), } } @@ -507,6 +524,9 @@ impl<'s> Parser<'s> { }; return Err(self.error_at_token(&self.tok, message)); } + if self.es2015 && self.peek().is_some_and(|t| t.is_punct(Punct::Star)) { + return Err(self.error_at_token(&self.tok, "a generator declaration cannot stand here; put it in a block")); + } self.parse_function_declaration() } TokenKind::Ident(_) if self.peek().is_some_and(|t| t.is_punct(Punct::Colon)) => self.parse_labeled(in_list), @@ -960,8 +980,9 @@ impl<'s> Parser<'s> { fn parse_function_declaration(&mut self) -> Result { let start = self.expect_keyword(Keyword::Function)?.span; + let generator = self.es2015 && self.eat(Punct::Star)?; let name = self.function_name()?; - let id = self.parse_function_rest(FunctionKind::Declaration, Some(name), start)?; + let id = self.parse_function_rest(FunctionKind::Declaration, Some(name), start, generator)?; Ok(self.ast.push_stmt(Stmt::FunctionDecl(id), self.span_from(start))) } @@ -977,15 +998,28 @@ impl<'s> Parser<'s> { Ok((Name { name, span: token.span }, token)) } - /// The parameters and body of a function, from `(`. - fn parse_function_rest(&mut self, kind: FunctionKind, name: Option<(Name, Token)>, start: Span) -> Result { + /// The parameters and body of a function, from `(`; with `generator`, a generator function's. + fn parse_function_rest( + &mut self, + kind: FunctionKind, + name: Option<(Name, Token)>, + start: Span, + generator: bool, + ) -> Result { self.enter()?; - let result = self.function_rest(kind, name, start); + // The parameters are read with the function's own `yield` rule, not the enclosing code's. + let outer_generator = std::mem::replace(&mut self.ctx.generator, generator); + let yields = self.yields.len(); + let result = self.function_rest(kind, name, start, generator); + // The `yield` expressions of this function are not in the code around it. + self.yields.truncate(yields); + self.ctx.generator = outer_generator; self.leave(); result } - fn function_rest(&mut self, kind: FunctionKind, name: Option<(Name, Token)>, start: Span) -> Result { + fn function_rest(&mut self, kind: FunctionKind, name: Option<(Name, Token)>, start: Span, generator: bool) -> Result { + let params_start = self.tok.span.start; self.expect(Punct::LParen)?; let mut params: Vec = Vec::new(); let mut defaults: Vec> = Vec::new(); @@ -1010,6 +1044,10 @@ impl<'s> Parser<'s> { } } let close = self.expect(Punct::RParen)?; + if generator && self.yield_between(params_start, close.span.start) { + let at = self.yields.get(self.yields.partition_point(|&y| y < params_start)).copied().unwrap_or(params_start); + return Err(self.error_at_offset(at, "a yield expression cannot stand in a generator function's parameters")); + } match kind { FunctionKind::Getter if !params.is_empty() || rest.is_some() => { return Err(self.error_at_token(&close, "a getter must not have parameters")); @@ -1025,7 +1063,7 @@ impl<'s> Parser<'s> { self.expect(Punct::LBrace)?; let names: Vec = params.iter().chain(&rest).map(|p| p.name.clone()).collect(); let outer_strict = self.ctx.strict; - let inner = Context { strict: outer_strict, in_function: true, ..Context::default() }; + let inner = Context { strict: outer_strict, in_function: true, generator, ..Context::default() }; let outer = std::mem::replace(&mut self.ctx, inner); self.push_scope(true, names); let body = self.parse_body(true); @@ -1034,7 +1072,7 @@ impl<'s> Parser<'s> { self.ctx = outer; let body = body?; self.expect(Punct::RBrace)?; - let function = Function { kind, name: name.map(|(n, _)| n), params, defaults, rest, body, strict, span: self.span_from(start) }; + let function = Function { kind, name: name.map(|(n, _)| n), params, defaults, rest, body, strict, generator, span: self.span_from(start) }; self.check_params(&function, use_strict)?; Ok(self.ast.push_function(function)) } @@ -1066,7 +1104,8 @@ impl<'s> Parser<'s> { self.expect(Punct::RBrace)?; } let defaults = if defaults.iter().all(Option::is_none) { Vec::new() } else { defaults }; - let function = Function { kind: FunctionKind::Arrow, name: None, params, defaults, rest, body, strict, span: self.span_from(start) }; + let function = + Function { kind: FunctionKind::Arrow, name: None, params, defaults, rest, body, strict, generator: false, span: self.span_from(start) }; self.check_params(&function, use_strict)?; let id = self.ast.push_function(function); Ok(self.ast.push_expr(Expr::Arrow(id), self.span_from(start))) @@ -1181,10 +1220,15 @@ impl<'s> Parser<'s> { fn assignment(&mut self, no_in: bool) -> Result { let mut targets: Vec<(ExprId, AssignOp)> = Vec::new(); loop { - let mut expr = self.parse_conditional(no_in)?; - if self.es2015 && self.at(Punct::Arrow) { - expr = self.arrow_from(expr, no_in)?; - } + let expr = if self.ctx.generator && self.tok.ident() == Some("yield") && !self.tok.escaped { + self.parse_yield(no_in)? + } else { + let mut expr = self.parse_conditional(no_in)?; + if self.es2015 && self.at(Punct::Arrow) { + expr = self.arrow_from(expr, no_in)?; + } + expr + }; let Some(op) = assign_op(&self.tok) else { let mut value = expr; while let Some((target, op)) = targets.pop() { @@ -1199,10 +1243,28 @@ impl<'s> Parser<'s> { } } + /// A yield expression, from `yield` (ECMA-262 2015 section 14.4): its operand is left out when + /// a line break follows `yield` or the next token cannot start an expression, and `yield*` + /// must have one. + fn parse_yield(&mut self, no_in: bool) -> Result { + let start = self.bump()?.span; + self.yields.push(start.start); + let delegate = !self.tok.newline_before && self.at(Punct::Star); + if delegate { + self.bump()?; + } + let arg = + if delegate || (!self.tok.newline_before && starts_expression(&self.tok, self.e4x)) { Some(self.parse_assignment(no_in)?) } else { None }; + Ok(self.ast.push_expr(Expr::Yield { arg, delegate }, self.span_from(start))) + } + /// The arrow function whose head is `expr`, read before the current `=>`: a name standing /// alone, or parameters in parentheses. fn arrow_from(&mut self, expr: ExprId, no_in: bool) -> Result { let start = self.ast.expr_span(expr); + if self.yield_between(start.start, start.end) { + return Err(self.error_at_offset(start.start, "a yield expression cannot stand in an arrow function's parameters")); + } let params = match self.ast.expr(expr) { Some(Expr::Ident(name)) => (vec![Name { name: name.clone(), span: start }], vec![None], None), Some(Expr::Paren(_)) => self.arrow_params(expr)?, @@ -1523,8 +1585,13 @@ impl<'s> Parser<'s> { fn parse_function_expression(&mut self) -> Result { let start = self.expect_keyword(Keyword::Function)?.span; - let name = if matches!(self.tok.kind, TokenKind::Ident(_)) { Some(self.function_name()?) } else { None }; - let id = self.parse_function_rest(FunctionKind::Expression, name, start)?; + let generator = self.es2015 && self.eat(Punct::Star)?; + // A generator expression's name is read with its own `yield` rule. + let outer_generator = std::mem::replace(&mut self.ctx.generator, generator); + let name = if matches!(self.tok.kind, TokenKind::Ident(_)) { self.function_name().map(Some) } else { Ok(None) }; + self.ctx.generator = outer_generator; + let name = name?; + let id = self.parse_function_rest(FunctionKind::Expression, name, start, generator)?; Ok(self.ast.push_expr(Expr::Function(id), self.span_from(start))) } @@ -1575,17 +1642,36 @@ impl<'s> Parser<'s> { let word = self.bump()?; if property_key(&self.tok).is_some() { let (key, _) = self.parse_property_key()?; - let function = self.parse_function_rest(kind, None, start)?; + let function = self.parse_function_rest(kind, None, start, false)?; let value = if kind == FunctionKind::Getter { PropertyValue::Get(function) } else { PropertyValue::Set(function) }; return Ok(Property { key, value, span: self.span_from(start) }); } let key = PropertyKey::Ident(word.ident().unwrap_or_default().to_string()); return self.property_value(key, start); } + if self.es2015 && self.eat(Punct::Star)? { + return self.generator_method(start); + } let (key, _) = self.parse_property_key()?; self.property_value(key, start) } + /// `*name(…) {…}` after the `*`: a generator method (ECMA-262 2015 section 14.4), the value of + /// the property `name`. Its parameter names are distinct (section 14.3.1), and it has no name + /// binding of its own. + fn generator_method(&mut self, start: Span) -> Result { + let (key, _) = self.parse_property_key()?; + let id = self.parse_function_rest(FunctionKind::Expression, None, start, true)?; + if let Some(f) = self.ast.function(id) { + let mut seen = HashSet::new(); + if let Some(p) = f.params.iter().chain(&f.rest).find(|p| !seen.insert(p.name.as_str())) { + return Err(self.error_at_offset(p.span.start, format!("duplicate parameter name '{}'", p.name))); + } + } + let value = self.ast.push_expr(Expr::Function(id), self.span_from(start)); + Ok(Property { key, value: PropertyValue::Init(value), span: self.span_from(start) }) + } + /// `: value` after a data property's name. fn property_value(&mut self, key: PropertyKey, start: Span) -> Result { self.expect(Punct::Colon)?; @@ -1614,6 +1700,42 @@ fn property_key(token: &Token) -> Option { } } +/// The token can start an expression, so a `yield` before it on the same line takes an operand. +fn starts_expression(token: &Token, e4x: bool) -> bool { + match &token.kind { + TokenKind::Ident(_) | TokenKind::Number(_) | TokenKind::String(_) | TokenKind::Template { .. } | TokenKind::RegExp { .. } => true, + TokenKind::Keyword(k) => matches!( + k, + Keyword::This + | Keyword::Null + | Keyword::True + | Keyword::False + | Keyword::Function + | Keyword::New + | Keyword::Delete + | Keyword::Void + | Keyword::Typeof + ), + TokenKind::Punct(p) => { + matches!( + p, + Punct::LParen + | Punct::LBracket + | Punct::LBrace + | Punct::Plus + | Punct::Minus + | Punct::Bang + | Punct::Tilde + | Punct::PlusPlus + | Punct::MinusMinus + | Punct::Slash + | Punct::SlashEq + ) || (e4x && matches!(p, Punct::Lt | Punct::At)) + } + _ => false, + } +} + fn is_eval_or_arguments(name: &str) -> bool { name == "eval" || name == "arguments" } diff --git a/crates/js/src/realm.rs b/crates/js/src/realm.rs index 5d5ce411d0..123fe3b202 100644 --- a/crates/js/src/realm.rs +++ b/crates/js/src/realm.rs @@ -296,6 +296,9 @@ impl Realm { interp.finally_marks.clear(); interp.finally_sites.clear(); interp.stack.clear(); + // A generator whose body was running when the run ended cannot go on. + let running: Vec<_> = interp.frames.iter().filter_map(|f| f.generator).collect(); + running.into_iter().for_each(|g| interp.end_generator(Some(g))); interp.frames.clear(); interp.temp_roots.clear(); interp.join_stack.clear(); diff --git a/crates/js/src/symbol.rs b/crates/js/src/symbol.rs index e89bbeb9f4..ba307b0763 100644 --- a/crates/js/src/symbol.rs +++ b/crates/js/src/symbol.rs @@ -185,6 +185,10 @@ pub(crate) struct Es2015Objects { pub(crate) array_values: ObjId, /// `Function.prototype[@@hasInstance]`. pub(crate) has_instance: ObjId, + /// `%GeneratorPrototype%`, which each generator function's `prototype` inherits from. + pub(crate) generator_proto: ObjId, + /// `%GeneratorFunction.prototype%`, the `[[Prototype]]` of every generator function. + pub(crate) generator_function_proto: ObjId, } /// The estimated bytes of a registry entry without its Symbol. @@ -208,7 +212,17 @@ impl Symbols { /// The objects the collector starts from. pub(crate) fn root_objects(&self) -> Vec { - self.objects.map_or_else(Vec::new, |o| vec![o.symbol_proto, o.array_iterator_proto, o.string_iterator_proto, o.array_values, o.has_instance]) + self.objects.map_or_else(Vec::new, |o| { + vec![ + o.symbol_proto, + o.array_iterator_proto, + o.string_iterator_proto, + o.array_values, + o.has_instance, + o.generator_proto, + o.generator_function_proto, + ] + }) } /// The bytes the registry's entries hold besides their Symbols, which a collection adds. diff --git a/crates/js/tests/test262.rs b/crates/js/tests/test262.rs index 19f1e77910..7a13690d81 100644 --- a/crates/js/tests/test262.rs +++ b/crates/js/tests/test262.rs @@ -44,6 +44,10 @@ //! [`Options::es2015`]: tests of any edition whose feature tags are all in [`SYMBOL_FEATURES`] and //! that parse as ES5. Its failures go to `symbol-failures.txt`. //! +//! Another reads and runs the tests of generator functions, `yield` and the generator objects (the +//! folders [`GENERATOR_FOLDERS`] names) in a realm with [`Options::es2015`], negative parse tests +//! included. Its failures go to `generators-failures.txt`. +//! //! The runner reads only regular files inside the suite: it does not follow symbolic links, refuses //! an `includes:` name that leaves the `harness/` folder, and refuses a file over //! [`MAX_FILE_BYTES`] before reading it. A folder or file it cannot read fails the test. @@ -910,6 +914,102 @@ fn run_symbol_built_ins(dir: &Path) { assert_eq!(all.panicked, 0, "the interpreter panicked; see {}", path.display()); } +/// The folders of the tests of generator functions, `yield` and the generator objects, which run +/// in a realm with [`Options::es2015`]. +const GENERATOR_FOLDERS: &[&str] = &[ + "language/statements/generators", + "language/expressions/generators", + "language/expressions/yield", + "built-ins/GeneratorPrototype", + "built-ins/GeneratorFunction", +]; + +#[test] +fn es2015_generators_run() { + let Some(dir) = suite_dir() else { + println!("test262 generators: SKIPPED (no suite; run cargo xtask test262)"); + return; + }; + let handle = std::thread::Builder::new().stack_size(64 << 20).spawn(move || run_generators(&dir)).unwrap(); + handle.join().unwrap(); +} + +/// Runs the tests under each folder [`GENERATOR_FOLDERS`] names in a realm with +/// [`Options::es2015`]: those whose feature tags are all `generators` or in [`ES2015_FEATURES`] or +/// [`SYMBOL_FEATURES`]. A negative parse test must give a `SyntaxError`; the others run as +/// [`run_tagged_tests`] runs them. Prints the counts of each folder and writes the failures to +/// `generators-failures.txt` beside the suite. +fn run_generators(dir: &Path) { + let options = Options { es2015: true, ..Options::default() }; + let missing: HashSet<&str> = missing_builtins(&[TEXT_BUILTINS, "Symbol"]); + let harness = |name: &str| or_fail(inside(dir, &format!("harness/{name}")).and_then(|p| read_source(&p))); + let prelude = format!("{}\n{}\n", harness("assert.js"), harness("sta.js")); + let allowed = |f: &str| f == "generators" || ES2015_FEATURES.contains(&f) || SYMBOL_FEATURES.contains(&f); + let mut all = RunCounts::default(); + let mut report = String::new(); + for folder in GENERATOR_FOLDERS { + let root = or_fail(inside(dir, &format!("test/{folder}"))); + assert!(root.is_dir(), "{} is not a test262 checkout", dir.display()); + let mut counts = RunCounts::default(); + for path in or_fail(test_files(&root)) { + let source = or_fail(read_source(&path)); + let meta = meta(&source); + let has = |flag: &str| meta.flags.iter().any(|f| f == flag); + let expect_error = meta.negative_phase.as_deref() == Some("parse"); + let includes: String = meta.includes.iter().map(|i| harness(i) + "\n").collect(); + if has("module") + || has("async") + || meta.negative_phase.as_deref() == Some("resolution") + || !meta.features.iter().all(|f| allowed(f)) + || (!expect_error && needs_missing_builtin_in(&[&source, &includes], &missing, &options)) + { + counts.skipped += 1; + continue; + } + counts.tests += 1; + let rel = path.strip_prefix(dir).unwrap_or(&path).display().to_string().replace('\\', "/"); + for &strict in modes(&meta) { + let mode = if strict { "strict" } else { "sloppy" }; + if expect_error { + let text = if strict { format!("\"use strict\";\n{source}") } else { source.clone() }; + if parse(&text, &options).is_ok() { + counts.failed += 1; + counts.failures.push_str(&format!("{rel} ({mode}): parsed; a SyntaxError was expected\n")); + } else { + counts.passed += 1; + } + continue; + } + let body = if has("raw") { source.clone() } else { format!("{prelude}{includes}{source}") }; + let script = if strict { format!("\"use strict\";\n{body}") } else { body }; + let negative_type = meta.negative_type.clone().filter(|_| meta.negative_phase.as_deref() == Some("runtime")); + match std::panic::catch_unwind(|| run_one(&script, negative_type.as_deref(), &options)) { + Ok(Ok(())) => counts.passed += 1, + Ok(Err(why)) => { + counts.failed += 1; + counts.failures.push_str(&format!("{rel} ({mode}): {why}\n")); + } + Err(_) => { + counts.failed += 1; + counts.panicked += 1; + counts.failures.push_str(&format!("{rel} ({mode}): PANIC\n")); + } + } + } + } + println!("test262 {folder} with Options::es2015: {}.", counts.summary()); + report.push_str(&format!("# {folder}\n{}\n", counts.failures)); + all.add(counts); + } + assert!(all.tests > 0, "no generator tests ran under {}", dir.display()); + let path = dir.join("generators-failures.txt"); + if let Err(e) = std::fs::write(&path, &report) { + println!("could not write {}: {e}", path.display()); + } + println!("test262 generators with Options::es2015: {}. Failures: {}", all.summary(), path.display()); + assert_eq!(all.panicked, 0, "the interpreter panicked; see {}", path.display()); +} + /// Runs the script tests under `root` of any edition whose feature tags are all in `features`, /// each in a new realm made with `options` after the harness, the way [`run_tests`] runs the /// others. A test with another tag is counted as skipped. diff --git a/docs/mcp.md b/docs/mcp.md index 4e071c4ff0..bcaef4853a 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2622,9 +2622,17 @@ not UTF-8. The language is ES5.1, except that identifiers take the characters Un declarations scoped to their block, arrow functions, template literals and tagged templates, default and rest parameters, and spread in array literals, calls and `new`. Spread reads arrays, strings (by code point) and objects with a `length` property, by index, and throws a `TypeError` for any other value; that rule is VectorCraft's own -until iterators are added. `eval`, `Function`, `#include` files and `$.evalFile` read code the way the script does, and +until iterators are added. A `.js` script also has generator functions (ECMA-262 11th edition, sections 14.4 and 25.4, +https://262.ecma-international.org/11.0/): `function*` declarations and expressions, `*name() {…}` methods in object +literals, `yield`, and `yield*`, which passes `next`, `throw` and `return` on to the iterator it delegates to. Calling +a generator function returns a generator object whose `next`, `return` and `throw` run its body to the next `yield`; +`return` runs the body's `finally` blocks, and resuming a generator while its body runs throws a `TypeError`. Each +resumption takes fuel and counts against the call depth. A generator function called in an engine that +`#targetengine` kept from a `.jsx` run throws a `TypeError`, since that engine was made without the ECMAScript 2015 +built-ins. `eval`, `Function`, `#include` files and `$.evalFile` read code the way the script does, and an engine that `#targetengine` keeps reads each run the way that run's script does. A -`.jsx` file and a `source` string read ES5.1 only, and the ECMAScript 2015 forms are syntax errors there. The script reaches the +`.jsx` file and a `source` string read ES5.1 only, and the ECMAScript 2015 forms are syntax errors there; there +`yield` is a name like any other. The script reaches the app through the global object `vc`, and writes to the Script Console and runs other files through `$`: - `vc.run(id, params)` runs a command and returns its result. A command that fails throws an error the script can diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index f6cb0a7eb9..0e6a8d37b0 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1079,11 +1079,12 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - `vectorcraft-js` parses JavaScript as ECMAScript 5.1 defines it, with the legacy octal forms, block functions and lenient regular expressions of Annex B, into a syntax tree with source spans; it reads the `#target`, `#include` and other preprocessor lines as directives without running them, and a script that breaks the grammar or an early-error rule gives a `SyntaxError` with its line and column. Nesting past the parser's depth limit (`Options::max_depth`, 200 by default) gives a `SyntaxError` instead of exhausting the stack. `cargo xtask test262` fetches the conformance suite at a pinned commit and parses its ES5 tests: 5,411 of 5,418 runs pass (the 7 others use `let` and `const`). This entry covers parsing; the next entry covers running scripts. Tests: `crates/js/src/tests.rs`, `crates/engine/tests/it/js_lexer_vs_scriptcheck.rs`. - `vectorcraft-js` identifiers, written out or as `\uXXXX` and `\u{...}` escapes, take the characters Unicode's `ID_Start` and `ID_Continue` properties allow (https://www.unicode.org/reports/tr31/), plus `$` and, at the start, `_`, as later ECMAScript editions define them (https://tc39.es/ecma262/#sec-names-and-keywords). `Other_ID_Start` characters such as U+2118 and `Other_ID_Continue` characters such as U+00B7 and the zero width non-joiner and joiner are accepted, and no `Pattern_Syntax` or `Pattern_White_Space` character is. Letter categories come from Unicode 17.0, so U+088F starts an identifier and U+1ACF may follow its first character; characters assigned after Unicode 17.0 are not yet identifier characters. Tests: `crates/js/src/tests.rs` (`identifier_characters_are_unicode_17_id_start_and_id_continue`, which checks every code point, `identifiers_take_the_characters_unicode_17_assigned`, `identifiers_take_the_other_id_start_and_continue_characters`, `identifiers_refuse_pattern_syntax_surrogates_and_bad_escapes`, `no_pattern_syntax_or_white_space_character_is_an_identifier_character`). - `vectorcraft-js`'s `Realm` runs ECMAScript 5.1 scripts: the parsed script compiles to verified bytecode that a non-recursive interpreter runs, with closures, `this`, `arguments`, `with`, direct and indirect `eval`, `new Function`, `try`/`catch`/`finally`, labeled `break` and `continue`, and `for`-`in` in insertion order, over a mark-and-sweep heap, with the built-ins the next two entries list. Every run is bounded by fuel, heap bytes, frames, nested host calls and an interrupt flag (smaller defaults in the wasm build), and a run that reaches a limit stops with a limit error that `try` cannot catch. `cargo xtask test262` also runs the suite's ES5 language tests that need only the built-ins present: 4,280 of 4,286 runs pass (4 of the others expect the completion values of later editions, and 2 expect a configurable function `length`). The app does not call it yet. Tests: `crates/js/src/interp_tests.rs`, `crates/js/tests/test262.rs`. - - With `Options::es2015`, `vectorcraft-js` also reads and runs these ECMAScript 2015 forms (https://262.ecma-international.org/6.0/): `let` and `const` with block scope and their temporal dead zone (a read or write before the declaration runs throws a `ReferenceError`, and a write to a `const` throws a `TypeError` in any code), a new `let` binding for each iteration of a `for` or `for`-`in` loop, function declarations scoped to their block, arrow functions with the `this` and `arguments` of the code around them and no `prototype`, template literals and tagged templates with one frozen strings object for each site, default and rest parameters with an `arguments` object that does not follow the parameters, and spread in array literals, calls and `new`. Spread reads arrays, strings (by code point) and objects with a `length` property, by index, and throws a `TypeError` for any other value; that rule is VectorCraft's own until iterators are added. Spread and template objects take fuel for each element and count against the heap limit, and nested arrows and templates count against `Options::max_depth`. `script.run` sets the option for a `.js` file, and `eval`, `Function`, `#include` files and `$.evalFile` read code the way the script does; a `.jsx` file and a `source` string stay ES5.1. Destructuring, `for`-`of`, classes, generators and modules are still syntax errors. `cargo xtask test262` reads the suite's tests of these forms without and with the option: 390 of 390 negative parse runs and 533 of 557 other runs pass with it (373 and 27 without it); the 24 failing runs expect function `name` properties, a configurable function `length` and the `caller` and `arguments` restrictions, ECMAScript 2015 rules that `vectorcraft-js` does not implement. Tests: `crates/js/src/es2015_tests.rs`, `crates/js/tests/test262.rs`, `crates/engine/src/tests/script_run.rs`. + - With `Options::es2015`, `vectorcraft-js` also reads and runs these ECMAScript 2015 forms (https://262.ecma-international.org/6.0/): `let` and `const` with block scope and their temporal dead zone (a read or write before the declaration runs throws a `ReferenceError`, and a write to a `const` throws a `TypeError` in any code), a new `let` binding for each iteration of a `for` or `for`-`in` loop, function declarations scoped to their block, arrow functions with the `this` and `arguments` of the code around them and no `prototype`, template literals and tagged templates with one frozen strings object for each site, default and rest parameters with an `arguments` object that does not follow the parameters, and spread in array literals, calls and `new`. Spread reads arrays, strings (by code point) and objects with a `length` property, by index, and throws a `TypeError` for any other value; that rule is VectorCraft's own until iterators are added. Spread and template objects take fuel for each element and count against the heap limit, and nested arrows and templates count against `Options::max_depth`. `script.run` sets the option for a `.js` file, and `eval`, `Function`, `#include` files and `$.evalFile` read code the way the script does; a `.jsx` file and a `source` string stay ES5.1. Destructuring, `for`-`of`, classes and modules are still syntax errors. `cargo xtask test262` reads the suite's tests of these forms without and with the option: 390 of 390 negative parse runs and 533 of 557 other runs pass with it (373 and 27 without it); the 24 failing runs expect function `name` properties, a configurable function `length` and the `caller` and `arguments` restrictions, ECMAScript 2015 rules that `vectorcraft-js` does not implement. Tests: `crates/js/src/es2015_tests.rs`, `crates/js/tests/test262.rs`, `crates/engine/src/tests/script_run.rs`. - `vectorcraft-js` provides the ECMAScript 5.1 built-ins `Object` with its property-descriptor functions, `create`, `keys`, `seal` and `freeze` (section 15.2), `Function.prototype.bind` (15.3.4.5), `Array` with every ES5 method (15.4), the error types (15.11), `Math` (15.8), `JSON` with revivers, replacers and indentation (15.12), and the global functions with Annex B's `escape` and `unescape` (15.1, B.2). The array methods work on array-like objects. A method visits only the indices that exist when its range is longer than 4,096 indices and more than 8 times the properties on the object and its prototypes, so `new Array(4294967295).join("")` ends at once; a shorter range is visited index by index, holes included, and each index takes fuel. `join` writes a cycle back to an array as an empty string, `JSON.stringify` throws a `TypeError` on a cycle, and deep `JSON` nesting uses no native stack. Every loop takes fuel and every result is checked against the heap limit. `cargo xtask test262` runs the suite's ES5 built-in tests that need only these built-ins: 6,798 of 6,866 runs pass (the 34 failing tests expect rules of later editions). It also fetches the `json2.js` polyfill at a pinned commit and checks that its `stringify` and `parse` agree with the built-in `JSON`. Tests: `crates/js/src/builtins_tests.rs`, `crates/js/tests/test262.rs`, `crates/js/tests/json2.rs`. - `vectorcraft-js` has `String`, `Number`, `RegExp` and `Date` as ECMAScript 5.1 defines them (sections 15.5, 15.7, 15.9 and 15.10, https://262.ecma-international.org/5.1/), with Annex B's `substr`, `getYear`, `setYear` and `toGMTString`. `toFixed`, `toExponential` and `toPrecision` format a number from its exact decimal value, and `toString(radix)` writes any base from 2 to 36. Regular expressions (flags `g`, `i` and `m`) run on a backtracking matcher whose choice points and capture state count against the heap limit and which takes fuel for every step, so a catastrophic pattern stops at the fuel limit and 50,000 nested groups give a `SyntaxError` at the default depth limit. A string method that would build a string past the heap limit stops before it allocates. `Date` reads the clock and time zone the host sets (`Realm::set_clock`, `Realm::set_time_zone`; local time is UTC by default). `cargo xtask test262` runs the suite's `built-ins` tests for the four (https://github.com/tc39/test262): of the runs of the ES5 tests that need only the built-ins present, 1,379 of 1,411 pass for `String`, 298 of 298 for `Number`, 954 of 988 for `RegExp` and 8 of 8 for `Date`. The others expect later editions' rules (built-in functions whose `length` can be deleted, flags given with a RegExp object, a negative `lastIndex`, `RegExp.prototype` as a plain object, and `RegExp.prototype`'s `global`, `ignoreCase` and `multiline` properties that can be deleted). Tests: `crates/js/src/text_tests.rs`, `crates/js/tests/test262.rs`. - `cargo xtask test262` also reads the suite's Annex B tests (https://tc39.es/ecma262/#sec-additional-ecmascript-features-for-web-browsers), whichever edition they name. It parses the 819 tests under `test/annexB/language` without a feature tag in the modes their flags give, so a `for`-`in` variable with an initializer must parse in sloppy code and give a `SyntaxError` in strict code (682 of 843 runs pass), and it runs those tests and the `test/annexB/built-ins` tests for `String`, `Date`, `RegExp` and `Function` that need only the built-ins present (263 of 667 runs pass for the language tests and 56 of 252 for the built-ins). Failures go to `annexb-parse-failures.txt`, `annexb-language-failures.txt` and `annexb-builtins-failures.txt` beside the suite. A conformance failure does not fail the tests, but an interpreter panic fails `annex_b_runs`, so `cargo xtask test262` exits non-zero. A folder or file the runner cannot read also fails the test that reads it. The runner reads only regular files inside the suite, up to 8 MiB each, and does not follow symbolic links. Tests: `crates/js/tests/test262.rs`. - With `Options::es2015` set, which it is not by default, a `vectorcraft-js` realm also has `Symbol` (ECMA-262 11th edition, section 19.4, https://262.ecma-international.org/11.0/): `Symbol(description)`, which `new` refuses with a `TypeError`, the `description` getter, `toString`, `valueOf`, and `Symbol.for` and `Symbol.keyFor` over a registry that lasts as long as the realm. `typeof` gives `"symbol"`. Symbols are property keys: `Object.getOwnPropertySymbols` lists an object's Symbol keys in the order they were added, `Object.defineProperty`, `getOwnPropertyDescriptor`, `freeze`, `seal`, `in`, `delete` and `hasOwnProperty` take them, and `for`-`in`, `Object.keys`, `Object.getOwnPropertyNames` and `JSON.stringify` leave them out. `String(symbol)` and `symbol.toString()` give `Symbol(description)`; any other conversion of a Symbol to a string or a number, such as `Symbol() + ''`, throws a `TypeError`. A string such as `'0b10'` or `'0o2'` converts to a number, as section 7.1.3.1 gives. The well-known Symbols `Symbol.iterator`, `Symbol.asyncIterator`, `Symbol.hasInstance`, `Symbol.toPrimitive` and `Symbol.toStringTag` are defined: conversion to a primitive calls an object's `@@toPrimitive` method, `instanceof` calls the right side's `@@hasInstance` method, and `Object.prototype.toString` writes a string `@@toStringTag`; `JSON.stringify` calls a String or Number object's `@@toPrimitive` method too. `Date.prototype[Symbol.toPrimitive]` (section 20.4.4.45) converts a Date with `toString` first for the hints `"string"` and `"default"` and with `valueOf` first for `"number"`, so `date + 1` joins the date's string; an object without an `@@toPrimitive` method, a Date whose method is `null` included, tries `valueOf` first when no hint is given. Nothing reads `Symbol.asyncIterator` yet. `Array.prototype.values` (also `Array.prototype[Symbol.iterator]`), `keys` and `entries`, `String.prototype[Symbol.iterator]` and every `arguments` object's `Symbol.iterator` return iterators whose `next()` gives `{value, done}` objects; a string iterator steps by code point and keeps a surrogate pair together. An array iterator reads the `length` at each step, so it visits elements added during the walk. Each step takes fuel, as does each prototype a Symbol-keyed lookup passes, and each Symbol and registry entry counts against the heap limit. A realm without the option, including the one the app runs scripts in, has none of these names, and a host function that returns a Symbol there throws a `TypeError`. The language does not have `for`-`of`, spread or destructuring yet, so scripts call `next()` themselves. `cargo xtask test262` runs the suite's tests of `Symbol`, `ArrayIteratorPrototype`, `StringIteratorPrototype`, `Object.getOwnPropertySymbols`, `Array.prototype.values`, `keys`, `entries` and `Symbol.iterator`, and `String.prototype[Symbol.iterator]` that need only these built-ins and parse as ES5, in such a realm: 164 of 216 runs pass (6 passed before), and the 52 others expect a configurable function `length` and a function `name` property. Tests: `crates/js/src/symbol_tests.rs`, `crates/js/tests/test262.rs`. + - With `Options::es2015`, a `vectorcraft-js` realm also has generators (ECMA-262 11th edition, sections 14.4 and 25.4, https://262.ecma-international.org/11.0/): `function*` declarations and expressions, `*name() {…}` methods in object literals, `yield`, and `yield*`, which passes `next`, `throw` and `return` on to the iterator it delegates to and closes an iterator without `throw` before it throws a `TypeError`. A generator object's `next`, `return` and `throw` come from `%GeneratorPrototype%`, which inherits from `%IteratorPrototype%`; `return` runs the `finally` blocks around the `yield`, `throw` raises the value there, and resuming a generator while its body runs throws a `TypeError`. `%GeneratorFunction%` builds a generator function from source as `Function` does, and is reached through a generator function's `constructor`. A generator function is not a constructor. In sloppy code outside a generator function's body and parameters, `yield` stays an identifier, and a realm without the option reads `function*` as a syntax error. A suspended generator keeps its frame and operands in its object, which the collector keeps while the object is reachable and frees with it. A resumption pushes that frame on the interpreter's frame stack and takes fuel, so a generator driven from a script uses no native stack, and a deep `yield*` chain stops at the frame limit. A realm made without the option that reads the syntax later has no generator built-ins, and calling a generator function there throws a `TypeError`. `script.run` runs generators in a `.js` script. `cargo xtask test262` runs the suite's tests under `language/statements/generators`, `language/expressions/generators`, `language/expressions/yield`, `built-ins/GeneratorPrototype` and `built-ins/GeneratorFunction` that need only the built-ins present, in such a realm: 509 of 549 runs of 296 tests pass (94 of 96 runs of 50 tests passed before), and the 40 others expect a configurable function `length`, a function `name` property and the `caller` and `arguments` restrictions. Tests: `crates/js/src/generator_tests.rs`, `crates/js/tests/test262.rs`, `crates/engine/src/tests/script_run.rs`. - Scripts: `cargo xtask corpus --scripts` fetches 397 public scripts and 1 file they include from 19 MIT and Apache-2.0 repositories at pinned commits into `corpus/scripts` (gitignored), each repository's license file beside its scripts. `xtask/script-corpus.txt` lists every file with its size and SHA-256, and a download is checked against both before it replaces anything; one more candidate is left out because it is over the 1 MiB limit for one script. `cargo xtask scripts --pass-rate [--report ]` runs each script headless in a process of its own (a new document, 5,000,000 instructions, no dialog answers, file reads only in its repository's folder and a new folder of its own, file writes only in that folder, no command it can start, stopped after 10 seconds) and writes a JSON report: the pass rate overall, per repository and for the scripts without dialogs or windows, how many parse, and each script's outcome. Script failures never fail the command, and without the corpus it skips. These limits are VectorCraft's own. Tests: `xtask/src/script_corpus.rs`, `crates/engine/tests/script_corpus.rs`. - With `Options::e4x` set, an E4X name standing alone (`@a`, `@ns::a`, `@[expr]`, `ns::a`, `*`) inside `with` or a filter predicate can be assigned, with `=` or a compound operator, incremented, decremented, deleted and used as a `for` or `for each` variable, as well as read. Each of these uses the nearest XML or XMLList value in scope that holds the name and evaluates the name once. When no XML value in scope holds the name, the read or write throws a `ReferenceError` before the right-hand side runs and creates no child or attribute, as ECMA-357 section 11.1 (https://ecma-international.org/publications-and-standards/standards/ecma-357/) specifies, so a filter such as `list.(@id == '1')` throws when an item has no `@id` and no outer XML value holds one. Tests: `crates/js/src/xml_tests.rs`. - `vectorcraft-js` runs ECMAScript for XML (ECMA-357, 2nd edition, https://ecma-international.org/publications-and-standards/standards/ecma-357/) when `Options::e4x` is set, which it is not by default: XML and XMLList literals with embedded `{}` expressions, the `..`, `.@`, `.*`, `.()` and `::` selectors, assignment and `delete` on selected nodes, `for each`, `default xml namespace`, and the `XML`, `XMLList`, `Namespace` and `QName` objects with their methods and settings. `xml.xpath(expression[, variables])` evaluates an XPath 1.0 expression (https://www.w3.org/TR/1999/REC-xpath-19991116/) with all 13 axes and the 27 core functions, and returns the selected nodes as an XMLList in document order without repeats. Each property of `variables` binds the variable of its name, an XMLList runs the expression on each of its elements in turn, and a prefix in a name test resolves through the context element's in-scope namespaces. An expression that breaks the grammar gives a `SyntaxError`; an unknown function, a wrong argument count, an unbound prefix or variable, and a result that is not a node-set or that holds the root or a namespace node give a `TypeError`. `id()` selects nothing, and evaluation uses no native stack, takes fuel and counts against the heap limit. `` in an XML string gives a `SyntaxError`. An XML declaration at the start of an XML string, after optional white space, is checked against XML 1.0's grammar (https://www.w3.org/TR/xml/#NT-XMLDecl): a version of `1.` and digits, then an optional encoding name and an optional standalone `yes` or `no`, in that order; any other declaration, or one with a character XML does not allow, gives a `SyntaxError`. The parser takes fuel for the length of every name, white space run and declaration it scans, and for the text it searched when a quote, CDATA section, comment or processing instruction is not closed. Parsing, serializing, comparing and copying trees use no native stack, and each takes fuel and counts against the heap limit. Inserting a node into itself or its descendants throws a `TypeError` before the tree changes, a literal or XML string nested past `Options::max_depth` gives a `SyntaxError`, and a tree built past that depth stops at the heap limit. Tests: `crates/js/src/xml_tests.rs`. From e06015b295717ace1bf8bdb6cfa9ab51fa27128b Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 22 Nov 2026 08:15:10 -0800 Subject: [PATCH 063/151] Plug-ins: object filters written in JavaScript An object filter may be a .vcplugin manifest with "runtime": "js" and the .js file its script key names in the same folder. plugin.install {path}, plugin.inspect, plugin.reload and File > Open read the two together; the host keeps them as one JSON object (the manifest with the script's text in source), which plugin.install {dataBase64} also takes and which the grant's SHA-256 covers. Each run gets a new interpreter with no file, command or clock access, the filter's instruction and time budgets, and a heap within the plug-in's memory cap. run(input, params) returns the output a module returns, checked the same way, and the document changes as one undo step. Syntax errors, thrown errors, limits and a missing result name the plug-in and its script, with the line and column when the interpreter reports them. A manifest without script, an unsafe script name or a script over 8 MiB is refused before the script is read. Docs: docs/plugins.md (JavaScript filters), docs/mcp.md, progress line. Part of #2193. --- Cargo.lock | 1 + crates/engine/src/cmd/plugin.rs | 36 +- crates/engine/tests/plugin_js.rs | 127 +++++++ crates/plugins/Cargo.toml | 4 +- crates/plugins/src/host.rs | 6 +- crates/plugins/src/js.rs | 494 ++++++++++++++++++++++++++++ crates/plugins/src/lib.rs | 7 +- crates/plugins/src/manifest.rs | 55 +++- crates/plugins/src/registry.rs | 140 +++++++- crates/plugins/src/runtime.rs | 81 ++++- crates/ui-egui/src/dialogs/tests.rs | 1 + crates/ui-egui/src/i18n/ca.tsv | 15 + crates/ui-egui/src/i18n/cs.tsv | 15 + crates/ui-egui/src/i18n/da.tsv | 15 + crates/ui-egui/src/i18n/de.tsv | 15 + crates/ui-egui/src/i18n/el.tsv | 15 + crates/ui-egui/src/i18n/es.tsv | 15 + crates/ui-egui/src/i18n/fi.tsv | 15 + crates/ui-egui/src/i18n/fr.tsv | 15 + crates/ui-egui/src/i18n/hi.tsv | 15 + crates/ui-egui/src/i18n/hu.tsv | 15 + crates/ui-egui/src/i18n/id.tsv | 15 + crates/ui-egui/src/i18n/it.tsv | 15 + crates/ui-egui/src/i18n/ja.tsv | 15 + crates/ui-egui/src/i18n/ka.tsv | 15 + crates/ui-egui/src/i18n/ko.tsv | 15 + crates/ui-egui/src/i18n/nl.tsv | 15 + crates/ui-egui/src/i18n/pl.tsv | 15 + crates/ui-egui/src/i18n/pt-br.tsv | 15 + crates/ui-egui/src/i18n/ru.tsv | 15 + crates/ui-egui/src/i18n/sv.tsv | 15 + crates/ui-egui/src/i18n/tr.tsv | 15 + crates/ui-egui/src/i18n/uk.tsv | 15 + crates/ui-egui/src/i18n/vi.tsv | 15 + crates/ui-egui/src/i18n/zh-hans.tsv | 15 + crates/ui-egui/src/i18n/zh-hant.tsv | 15 + crates/ui-egui/src/io/open.rs | 10 +- crates/ui-egui/src/tests/plugins.rs | 23 ++ docs/mcp.md | 5 +- docs/plugins.md | 64 +++- docs/target-app-parity.md | 1 + 41 files changed, 1388 insertions(+), 42 deletions(-) create mode 100644 crates/engine/tests/plugin_js.rs create mode 100644 crates/plugins/src/js.rs diff --git a/Cargo.lock b/Cargo.lock index 6a602ed891..6fca10b26e 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -7147,6 +7147,7 @@ dependencies = [ "vectorcraft-color", "vectorcraft-doc", "vectorcraft-geom 0.24.1", + "vectorcraft-js", "wasmi", "wasmparser 0.228.0", "wat", diff --git a/crates/engine/src/cmd/plugin.rs b/crates/engine/src/cmd/plugin.rs index 2a1b8c8b40..6b7ce246d2 100644 --- a/crates/engine/src/cmd/plugin.rs +++ b/crates/engine/src/cmd/plugin.rs @@ -43,6 +43,10 @@ //! A filter whose manifest lists `inputs` (plug-in API level 2) is also given the selected type, //! images or symbol instances of those kinds, to read only: its output must return each of them //! unchanged ([`objects::decode_output_with`]). +//! +//! A filter may be written in JavaScript ([`vectorcraft_plugins::js`]): `plugin.install {path}` +//! takes its `.vcplugin` manifest and reads the `.js` file the manifest names beside it, and the +//! plug-in store keeps the two as one module. use std::sync::{Arc, Mutex, RwLock}; @@ -104,6 +108,10 @@ pub fn describe(p: &Plugin) -> Value { if m.paint_output { v["paintOutput"] = json!(true); } + if let Some(script) = p.script() { + v["runtime"] = json!(m.runtime.name()); + v["script"] = json!(script); + } if !m.command_allowlist.is_empty() { v["commandAllowlist"] = json!(m.command_allowlist); } @@ -597,8 +605,9 @@ pub(crate) fn admit_effects_for(cmd: &str, fx: &[Effect], n: &Node) -> std::resu /// Largest base64 payload `plugin.install` accepts (the module limit, encoded). const MAX_DATA_CHARS: usize = (32 << 20) / 3 * 4 + 4; -/// The `.wasm` extension plug-in files have (File › Open installs them). -pub const EXTS: &[&str] = &["wasm"]; +/// The extensions plug-in files have (File › Open installs them): a WebAssembly module, and a +/// JavaScript plug-in's manifest. +pub const EXTS: &[&str] = &["wasm", vectorcraft_plugins::js::PACKAGE_EXT]; /// The plug-in module command `c`'s params give, loaded and checked, and its bytes: `path` (a /// `.wasm` file) or `dataBase64` (the module, with `name` shown as its source). @@ -959,12 +968,23 @@ fn inspect(s: &mut Session, p: &Value) -> Result { }) } -/// The plug-in in the `.wasm` file `path`, and its module. +/// The plug-in in the `.wasm` file `path`, or in the `.vcplugin` manifest `path` and the `.js` file +/// it names, and its module: for a JavaScript plug-in, the manifest with the script's text +/// ([`registry::read_js_package`]). Under automation read roots the script must be inside them too. #[cfg(not(target_arch = "wasm32"))] fn load_path(path: &str) -> Result<(Plugin, Vec)> { crate::file_access::check_read(path).map_err(EngineError::Other)?; let limits = vectorcraft_plugins::Limits::default(); - let bytes = crate::store::read_capped(std::path::Path::new(path), limits.max_module_bytes as u64).map_err(EngineError::Other)?; + let file = std::path::Path::new(path); + let bytes = if registry::is_js_package(file) { + let allow = |script: &std::path::Path| match script.to_str() { + Some(script) => crate::file_access::check_read(script), + None => Err(format!("automation path rejected: {} isn't valid text", script.display())), + }; + registry::read_js_package(file, &allow).map_err(err)? + } else { + crate::store::read_capped(file, limits.max_module_bytes as u64).map_err(EngineError::Other)? + }; Ok((Plugin::load(&bytes, limits).map_err(err)?.with_source(path), bytes)) } @@ -1270,7 +1290,7 @@ pub fn specs() -> Vec { "List Plug-ins", [], None, - "{} → {plugins: [{id, name, version, kind: \"filter\"|\"effect\"|\"exporter\"|\"importer\", author, description, params (doc), paramsSchema, effect? (the effect id of a live effect: plugin.), format? and extensions? (an exporter's or importer's format id, plugin., for document.export or document.open's importer, and its file extensions), budget?: \"heavy\" (a filter that may compute for longer, see plugin.install's allowHeavy), inputs?: [\"type\"|\"image\"|\"symbolInstance\"] (the objects besides paths a filter reads, see plugin.run), size, source, permissions: [name] (what it may do: the ones its manifest lists, else the ones its kind implies; progress: it may report its progress, see Cancel and write log lines; settings: it may keep settings of its own; cache: it may keep a cache of its own; commands: a filter may run the commands its commandAllowlist names, see docs/plugins.md), commandAllowlist?: [command id] (the commands a filter with the commands permission may run while it runs, with vc_call), hash (the module's SHA-256), api (the plug-in API level it was built for, 1 or 2), paintOutput?: true (a live effect whose pieces have paints of their own, see docs/plugins.md), cacheBytes (the bytes its cache holds; see plugin.clearCache), commands?: [{id, command (its command id, plugin.., which runs it), label, params (doc), paramsSchema}] (the menu commands a filter or live effect adds)}], folder: the Additional Plug-ins Folder load report {folder, loaded, failed: [{file, error}], leftOut} | null (under automation read roots, a folder outside them is null, and a failed file and a plug-in's source outside them are named by their file name), safeMode: bool (no plug-in loads or runs, see plugin.safeMode), disabled: [{id, file, name, label}] (turned off for the next launch, see plugin.setEnabled)}", + "{} → {plugins: [{id, name, version, kind: \"filter\"|\"effect\"|\"exporter\"|\"importer\", author, description, params (doc), paramsSchema, effect? (the effect id of a live effect: plugin.), format? and extensions? (an exporter's or importer's format id, plugin., for document.export or document.open's importer, and its file extensions), budget?: \"heavy\" (a filter that may compute for longer, see plugin.install's allowHeavy), inputs?: [\"type\"|\"image\"|\"symbolInstance\"] (the objects besides paths a filter reads, see plugin.run), size, source, permissions: [name] (what it may do: the ones its manifest lists, else the ones its kind implies; progress: it may report its progress, see Cancel and write log lines; settings: it may keep settings of its own; cache: it may keep a cache of its own; commands: a filter may run the commands its commandAllowlist names, see docs/plugins.md), commandAllowlist?: [command id] (the commands a filter with the commands permission may run while it runs, with vc_call), hash (the module's SHA-256), api (the plug-in API level it was built for, 1 or 2), runtime?: \"js\" and script?: its .js file name (a JavaScript filter, see docs/plugins.md), paintOutput?: true (a live effect whose pieces have paints of their own, see docs/plugins.md), cacheBytes (the bytes its cache holds; see plugin.clearCache), commands?: [{id, command (its command id, plugin.., which runs it), label, params (doc), paramsSchema}] (the menu commands a filter or live effect adds)}], folder: the Additional Plug-ins Folder load report {folder, loaded, failed: [{file, error}], leftOut} | null (under automation read roots, a folder outside them is null, and a failed file and a plug-in's source outside them are named by their file name), safeMode: bool (no plug-in loads or runs, see plugin.safeMode), disabled: [{id, file, name, label}] (turned off for the next launch, see plugin.setEnabled)}", always, list ), @@ -1297,7 +1317,7 @@ pub fn specs() -> Vec { "Install Plug-in", [], None, - "{path: a .wasm file (desktop) | dataBase64: the module (+ name?: shown as its source), replace?: bool (true once the user agreed: a module with other bytes than the plug-in installed with its id, or with none installed, one whose id has settings or a cache in the plug-in store, installs only with it, takes that plug-in's place and gets its settings and cache; false: one whose id is installed is refused; left out, the same module installs again), name?: file name (with dataBase64), allowHeavy?: bool (a filter whose manifest asks for a heavy budget, budget \"heavy\" in plugin.inspect, installs only with it), grant?: [permission] (a plug-in whose manifest lists permissions, needsApproval in plugin.inspect, installs only when grant holds every one of them; the grant is recorded with the module's hash and covers only that module, so a module with other bytes needs a new grant even when it lists the same permissions; installing a module that lists no permissions forgets the grant held for its id; a refused install keeps the grant, a failed write of the module to the plug-in store leaves the grant in the store, and a stored module that is disabled or not read in Safe Mode keeps the grant for its id; with a plug-in store attached, only the grants kept there count; a request's allowHeavy and grant are refused unless the session was started with vectorcraft-cli --allow-plugin-grants: in the desktop app a person approves the install, see ui.installPlugin, and a module whose hash is already recorded, by a person's approval or by a grant accepted under that flag, needs no grant), hash?: string (the module's SHA-256 as plugin.inspect gave it: a module with other bytes is refused)} validate and install a WebAssembly plug-in for this session (with a plug-in store, the install waits while another window or process changes the store and writes the module and its grant before that window or process changes it again; when the store's disabled.lock can't be locked, nothing is installed) (a module whose commandAllowlist names a command no plug-in may call, such as one that reads or writes files, is refused) → its plugin.list entry, plus unknownCommands?: [id] (commandAllowlist ids no command has; a call of one fails)", + "{path: a .wasm file, or a JavaScript plug-in's .vcplugin manifest, read with the .js file its script names (desktop) | dataBase64: the module, or a JavaScript plug-in as one JSON object, its manifest with the script's text in source (+ name?: shown as its source), replace?: bool (true once the user agreed: a module with other bytes than the plug-in installed with its id, or with none installed, one whose id has settings or a cache in the plug-in store, installs only with it, takes that plug-in's place and gets its settings and cache; false: one whose id is installed is refused; left out, the same module installs again), name?: file name (with dataBase64), allowHeavy?: bool (a filter whose manifest asks for a heavy budget, budget \"heavy\" in plugin.inspect, installs only with it), grant?: [permission] (a plug-in whose manifest lists permissions, needsApproval in plugin.inspect, installs only when grant holds every one of them; the grant is recorded with the module's hash and covers only that module, so a module with other bytes needs a new grant even when it lists the same permissions; installing a module that lists no permissions forgets the grant held for its id; a refused install keeps the grant, a failed write of the module to the plug-in store leaves the grant in the store, and a stored module that is disabled or not read in Safe Mode keeps the grant for its id; with a plug-in store attached, only the grants kept there count; a request's allowHeavy and grant are refused unless the session was started with vectorcraft-cli --allow-plugin-grants: in the desktop app a person approves the install, see ui.installPlugin, and a module whose hash is already recorded, by a person's approval or by a grant accepted under that flag, needs no grant), hash?: string (the module's SHA-256 as plugin.inspect gave it: a module with other bytes is refused)} validate and install a plug-in for this session (with a plug-in store, the install waits while another window or process changes the store and writes the module and its grant before that window or process changes it again; when the store's disabled.lock can't be locked, nothing is installed) (a module whose commandAllowlist names a command no plug-in may call, such as one that reads or writes files, is refused) → its plugin.list entry, plus unknownCommands?: [id] (commandAllowlist ids no command has; a call of one fails)", always, install ), @@ -1306,7 +1326,7 @@ pub fn specs() -> Vec { "Inspect Plug-in", [], None, - "{path: a .wasm file (desktop) | dataBase64: the module, name?: the file name shown as its source (with dataBase64)} validate a WebAssembly plug-in without installing it → the plugin.list entry it would have, plus needsApproval: bool (true when it lists permissions no person has granted this very module, its bytes included: it then needs a person's approval, see plugin.install) and needsReplace: bool (true when it would take the place of another module with its id: plugin.install then needs replace: true), unknownCommands?: [id] (commandAllowlist ids no command has) and refusedCommands?: [id] (commandAllowlist ids no plug-in may call: plugin.install refuses the module)", + "{path: a .wasm file or a .vcplugin manifest (desktop) | dataBase64: the module or a JavaScript plug-in's JSON, name?: the file name shown as its source (with dataBase64)} validate a plug-in without installing it, running none of its code → the plugin.list entry it would have, plus needsApproval: bool (true when it lists permissions no person has granted this very module, its bytes included: it then needs a person's approval, see plugin.install) and needsReplace: bool (true when it would take the place of another module with its id: plugin.install then needs replace: true), unknownCommands?: [id] (commandAllowlist ids no command has) and refusedCommands?: [id] (commandAllowlist ids no plug-in may call: plugin.install refuses the module)", always, inspect ), @@ -1333,7 +1353,7 @@ pub fn specs() -> Vec { "Reload Plug-ins", ["Object", "Plug-ins"], None, - "{path?: a folder (default: the Additional Plug-ins Folder preference)} install every *.wasm in it, the first 1,000 by file name (desktop; a bad module, one that isn't a regular file, and one disabled with plugin.setEnabled, is reported and skipped, and so are a heavy filter and a plug-in that lists permissions the user hasn't granted this very module, its bytes included; an error in Safe Mode) → {folder, loaded: [id], failed: [{file, error}], leftOut: the count of *.wasm files past the first 1,000, not tried}", + "{path?: a folder (default: the Additional Plug-ins Folder preference)} install every *.wasm and *.vcplugin in it, the first 1,000 by file name (desktop; a bad module, one that isn't a regular file, and one disabled with plugin.setEnabled, is reported and skipped, and so are a heavy filter and a plug-in that lists permissions the user hasn't granted this very module, its bytes included; an error in Safe Mode) → {folder, loaded: [id], failed: [{file, error}], leftOut: the count of *.wasm and *.vcplugin files past the first 1,000, not tried}", always, reload ), diff --git a/crates/engine/tests/plugin_js.rs b/crates/engine/tests/plugin_js.rs new file mode 100644 index 0000000000..0b5558da11 --- /dev/null +++ b/crates/engine/tests/plugin_js.rs @@ -0,0 +1,127 @@ +//! JavaScript filter plug-ins through the engine: a `.vcplugin` manifest and the `.js` file it +//! names install with `plugin.install {path}`, run with `plugin.run` as one undo step, and a run +//! that fails or exhausts its budget leaves the document as it was. +// Integration tests: unwrapping and panicking on failure is fine here, unlike in shipped code (AGENTS.md › Robustness). +#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] + +use std::path::{Path, PathBuf}; + +use serde_json::{Value, json}; +use vectorcraft_color::Color; +use vectorcraft_engine::Session; +use vectorcraft_testkit::fixtures::{exec, rect, select, session}; + +/// Paints every input object's first fill blue. +const BLUE: &str = "function run(input, params) {\n\ + return {objects: input.objects.map(function (o) {\n\ + return {id: o.id, fills: [{type: 'solid', color: {model: 'rgb', r: 0, g: 0, b: 1}}]};\n\ + })};\n\ +}\n"; + +/// An empty folder for one test, with anything an earlier run left there removed. +fn folder(tag: &str) -> PathBuf { + let d = std::env::temp_dir().join(format!("vc-plugin-js-{tag}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&d); + std::fs::create_dir_all(&d).unwrap(); + d +} + +/// Writes the manifest of filter `id`, whose code is `tint.js`, with `extra` keys, and `script` as +/// that file → the manifest's path. +fn package(dir: &Path, id: &str, extra: Value, script: Option<&str>) -> String { + let mut m = json!({"id": id, "name": "Tint", "kind": "filter", "runtime": "js", "script": "tint.js"}); + if let (Some(m), Value::Object(extra)) = (m.as_object_mut(), extra) { + m.extend(extra); + } + let path = dir.join(format!("{id}.vcplugin")); + std::fs::write(&path, serde_json::to_vec(&m).unwrap()).unwrap(); + if let Some(script) = script { + std::fs::write(dir.join("tint.js"), script).unwrap(); + } + path.display().to_string() +} + +/// The active document's layers and its undo steps. +fn state(s: &mut Session) -> (Value, usize) { + let layers = exec(s, "document.inspect", json!({}))["layers"].take(); + (layers, s.doc().unwrap().history.undo.len()) +} + +fn fill(s: &Session, id: vectorcraft_doc::NodeId) -> Option { + s.doc().unwrap().doc.node(id).unwrap().appearance.fill_paint().color() +} + +#[test] +fn a_javascript_filter_changes_a_fill_as_one_undo_step() { + let dir = folder("blue"); + let mut s = session(); + let path = package(&dir, "test.js.engine.blue", json!({}), Some(BLUE)); + let info = exec(&mut s, "plugin.install", json!({"path": path, "replace": true})); + assert_eq!((info["runtime"].as_str(), info["script"].as_str(), info["kind"].as_str()), (Some("js"), Some("tint.js"), Some("filter"))); + let id = rect(&mut s, 10.0, 10.0, 20.0, 20.0); + exec(&mut s, "paint.setFill", json!({"ids": [id.0], "color": "#ff0000"})); + select(&mut s, &[id]); + let before = state(&mut s); + let r = exec(&mut s, "plugin.run", json!({"id": "test.js.engine.blue"})); + assert_eq!(r["ids"], json!([id.0])); + assert_eq!(fill(&s, id).map(|c| c.to_rgb_uncalibrated()), Some([0.0, 0.0, 1.0])); + assert_eq!(state(&mut s).1, before.1 + 1, "one undo step"); + exec(&mut s, "edit.undo", json!({})); + assert_eq!(state(&mut s), before); + exec(&mut s, "plugin.remove", json!({"id": "test.js.engine.blue"})); + std::fs::remove_dir_all(&dir).unwrap(); +} + +/// An endless loop ends with the plug-in's instruction budget, the error names the plug-in, and the +/// document and its history stay as they were. +#[test] +fn an_endless_loop_stops_on_its_budget_and_changes_nothing() { + let dir = folder("loop"); + let mut s = session(); + let path = package(&dir, "test.js.engine.loop", json!({}), Some("function run(input) {\n while (true) {}\n}\n")); + exec(&mut s, "plugin.install", json!({"path": path, "replace": true})); + let id = rect(&mut s, 10.0, 10.0, 20.0, 20.0); + select(&mut s, &[id]); + let before = state(&mut s); + let e = s.execute("plugin.run", &json!({"id": "test.js.engine.loop"})).unwrap_err().to_string(); + assert!(e.contains("instruction budget") && e.contains("test.js.engine.loop, tint.js line 2"), "{e}"); + assert_eq!(state(&mut s), before); + exec(&mut s, "plugin.remove", json!({"id": "test.js.engine.loop"})); + std::fs::remove_dir_all(&dir).unwrap(); +} + +/// A filter that reads `File` throws a `ReferenceError`: the realm has none of the script runner's +/// file access. Nothing changes. +#[test] +fn a_javascript_filter_has_no_file_access() { + let dir = folder("file"); + let mut s = session(); + let path = package(&dir, "test.js.engine.file", json!({}), Some("function run(input) {\n return new File('/etc/passwd').read();\n}\n")); + exec(&mut s, "plugin.install", json!({"path": path, "replace": true})); + let id = rect(&mut s, 10.0, 10.0, 20.0, 20.0); + select(&mut s, &[id]); + let before = state(&mut s); + let e = s.execute("plugin.run", &json!({"id": "test.js.engine.file"})).unwrap_err().to_string(); + assert!(e.contains("ReferenceError") && e.contains("File") && e.contains("test.js.engine.file"), "{e}"); + assert_eq!(state(&mut s), before); + exec(&mut s, "plugin.remove", json!({"id": "test.js.engine.file"})); + std::fs::remove_dir_all(&dir).unwrap(); +} + +/// A manifest with `"runtime": "js"` and no `script` is refused at install, the error names the +/// key, and nothing is installed. +#[test] +fn a_manifest_without_its_script_is_refused_at_install() { + let dir = folder("noscript"); + let mut s = session(); + let path = package(&dir, "test.js.engine.noscript", json!({"script": null}), None); + let mut m: Value = serde_json::from_slice(&std::fs::read(&path).unwrap()).unwrap(); + m.as_object_mut().unwrap().remove("script"); + std::fs::write(&path, serde_json::to_vec(&m).unwrap()).unwrap(); + for cmd in ["plugin.inspect", "plugin.install"] { + let e = s.execute(cmd, &json!({"path": path})).unwrap_err().to_string(); + assert!(e.contains("`runtime` \"js\" needs `script`"), "{cmd}: {e}"); + } + assert!(vectorcraft_plugins::registry::get("test.js.engine.noscript").is_none()); + std::fs::remove_dir_all(&dir).unwrap(); +} diff --git a/crates/plugins/Cargo.toml b/crates/plugins/Cargo.toml index 0a964167a2..c5d80823d6 100644 --- a/crates/plugins/Cargo.toml +++ b/crates/plugins/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "vectorcraft-plugins" -description = "Sandboxed WebAssembly plug-ins for VectorCraft: a resource-limited wasmi host for object filters and live effects" +description = "Sandboxed plug-ins for VectorCraft: a resource-limited wasmi host for object filters and live effects, and JavaScript object filters" version.workspace = true edition.workspace = true license.workspace = true @@ -21,6 +21,8 @@ craft-vectorcraft-format = { workspace = true } # The SHA-256 of a module, which the install prompt shows and a grant records. sha2 = { version = "0.10", default-features = false } thiserror = { workspace = true } +# The interpreter of JavaScript plug-ins (`js.rs`). +vectorcraft-js = { workspace = true } wasmi = { workspace = true } wasmparser = { workspace = true } # The monotonic clock of run deadlines and the first-view budget: `std::time::Instant` on the diff --git a/crates/plugins/src/host.rs b/crates/plugins/src/host.rs index 354610e4c0..fb12557f37 100644 --- a/crates/plugins/src/host.rs +++ b/crates/plugins/src/host.rs @@ -688,7 +688,7 @@ impl Run { } } - fn progress(&mut self, done: i64, total: i64) { + pub(crate) fn progress(&mut self, done: i64, total: i64) { let total = u64::try_from(total).unwrap_or(0); let done = u64::try_from(done).unwrap_or(0); let done = if total > 0 { done.min(total) } else { done }; @@ -710,12 +710,12 @@ impl Run { vectorcraft_doc::cancel::progress(done, total, PROGRESS_STEP); } - fn cancelled(&self) -> i32 { + pub(crate) fn cancelled(&self) -> i32 { i32::from(vectorcraft_doc::cancel::is_cancelled() || self.deadline.passed()) } /// Writes the `len` bytes at `ptr` in `memory` as a line of `level` → what `vc_log` returns. - fn log(&mut self, level: i32, memory: &[u8], ptr: usize, len: usize) -> i32 { + pub(crate) fn log(&mut self, level: i32, memory: &[u8], ptr: usize, len: usize) -> i32 { let Some(level) = LogLevel::from_code(level) else { return LOG_BAD_LEVEL }; let Some(bytes) = ptr.checked_add(len).and_then(|end| memory.get(ptr..end)) else { return LOG_OUTSIDE_MEMORY }; if self.report.truncated { diff --git a/crates/plugins/src/js.rs b/crates/plugins/src/js.rs new file mode 100644 index 0000000000..e6b13e73fa --- /dev/null +++ b/crates/plugins/src/js.rs @@ -0,0 +1,494 @@ +//! JavaScript plug-ins: an object filter whose manifest gives `"runtime": "js"`, with its code in a +//! JavaScript file instead of a WebAssembly module, run on `vectorcraft-js`. +//! +//! On disk the plug-in is a manifest file (`.vcplugin`, JSON) with `"runtime": "js"` and `script`, +//! the name of its `.js` file in the same folder ([`crate::registry::read_js_package`]). The host +//! loads it as one JSON object, the manifest with the script's text in `source` +//! ([`read_bundle`]): that object is what `plugin.install {dataBase64}` takes, what the plug-in +//! store keeps, and what the SHA-256 a grant records covers, so a change to the manifest or to the +//! script needs a new approval. Loading parses the script and runs none of it. +//! +//! Each run gets a fresh realm with the language's built-ins and a `vc` object: `vc.input` +//! and `vc.params` hold the input and parameter JSON a WebAssembly filter's `vc_run` is given, and +//! with the `progress` permission `vc.progress(done, total)`, `vc.cancelled()` and +//! `vc.log(level, text)` do what `vc_progress`, `vc_cancelled` and `vc_log` do ([`crate::host`]). +//! The realm has no `$`, `File`, `Folder`, `app` or other global of the script runner, no clock +//! (`Date.now()` is `NaN`) and no host function besides these. The script's top level runs, then +//! `run(input, params)` is called with the parsed JSON, and the value it returns, written as JSON, +//! is the run's output, which the host checks as it checks a WebAssembly filter's. +//! +//! A run is held to the filter's instruction budget (one budget for the top level and the call, +//! checked in slices between which the deadline and Cancel are checked), a heap of at most the +//! plug-in's memory cap, and the interpreter's frame and re-entry limits. A thrown error, a limit +//! or a malformed result fails the run with an [`Error`] that names the plug-in, its script and, +//! when known, the line and column. + +use std::cell::RefCell; +use std::rc::Rc; + +use serde_json::{Map, Value}; +use vectorcraft_js::{Data, HostError, HostItem, JsValue, LimitKind, Progress, Realm, RunError, RunErrorKind}; + +use crate::host::{Deadline, LOG_BAD_LEVEL, LOG_DROPPED, LOG_WRITTEN, Report, Run}; +use crate::manifest::{Manifest, Runtime}; +use crate::permissions::{self, Permission}; +use crate::runtime::SELECTION_TOO_LARGE; +use crate::{Error, Limits, Result}; + +/// The extension of a JavaScript plug-in's manifest file. +pub const PACKAGE_EXT: &str = "vcplugin"; + +/// Largest script, in bytes. +pub const MAX_SCRIPT_BYTES: usize = 8 << 20; + +/// Longest script file name, in bytes. +pub const MAX_SCRIPT_NAME: usize = 128; + +/// The script's name when the plug-in's JSON gives none. +pub const DEFAULT_SCRIPT: &str = "plugin.js"; + +/// Instructions a run executes between two checks of its deadline and Cancel. +pub const FUEL_SLICE: u64 = 1_000_000; + +/// Longest error message a run reports, in characters. +const MAX_ERROR_TEXT: usize = 512; + +/// What `script` may hold. +const SCRIPT_NAME_RULE: &str = + "`script` must be the name of a .js file in the manifest's folder: 1-128 bytes, no folder, no `:`, not starting with `.`"; + +/// Where the script's text may be given. +pub const SOURCE_RULE: &str = + "`source` is the script's text, given only in the JSON that plugin.install's dataBase64 takes: a .vcplugin file names its script in `script`"; + +/// The error of a plug-in's JSON without `"runtime": "js"`. +pub(crate) const NOT_JS: &str = "a JavaScript plug-in's manifest gives `runtime` \"js\""; + +/// What the arguments of `vc.progress` and `vc.log` may be. +const PROGRESS_ARGS: &str = "vc.progress(done, total) takes two numbers"; +const LOG_ARGS: &str = "vc.log(level, text) takes a level, 0 (error), 1 (warning), 2 (information) or 3 (debug), and a string"; + +/// What runs the plug-in: its script's top level is done, `run` is called with the input and the +/// parameters, and what it returns is written as JSON. +const ENTRY: &str = "(function () {\n\ + if (typeof run !== 'function') throw new TypeError('the script defines no function run(input, params)');\n\ + return JSON.stringify(run(JSON.parse(vc.input), JSON.parse(vc.params)));\n\ +})()"; + +/// A JavaScript plug-in's code. +#[derive(Clone, Debug, PartialEq, Eq)] +pub(crate) struct Script { + /// Its file name, which errors give. + pub(crate) name: String, + pub(crate) source: String, +} + +/// Is `name` a script file name `script` may give: a `.js` file directly in the manifest's folder? +pub fn valid_script_name(name: &str) -> bool { + (1..=MAX_SCRIPT_NAME).contains(&name.len()) + && !name.starts_with('.') + && !name.chars().any(|c| matches!(c, '/' | '\\' | ':') || c.is_control()) + && name.len() > 3 + && name.get(name.len() - 3..).is_some_and(|ext| ext.eq_ignore_ascii_case(".js")) +} + +/// The `script` a manifest's JSON gives, checked. +pub(crate) fn script_name(v: &Value) -> Result { + match v.as_str() { + Some(name) if valid_script_name(name) => Ok(name.to_string()), + _ => Err(Error::Manifest(SCRIPT_NAME_RULE.into())), + } +} + +/// The error of a manifest with `"runtime": "js"` and no `script`. +pub(crate) fn no_script() -> Error { + Error::Manifest("`runtime` \"js\" needs `script`: the name of the plug-in's .js file, next to the manifest".into()) +} + +/// Does `map`, a plug-in's JSON, give `"runtime": "js"`? +pub(crate) fn is_js(map: &Map) -> bool { + map.get("runtime").and_then(Value::as_str) == Some(Runtime::Js.name()) +} + +/// How the script is read. +fn options() -> vectorcraft_js::Options { + vectorcraft_js::Options { max_source_units: MAX_SCRIPT_BYTES, ..vectorcraft_js::Options::default() } +} + +/// Reads a JavaScript plug-in given as one JSON object: its manifest, with the script's text in +/// `source` and its file name in `script` (left out: [`DEFAULT_SCRIPT`]). The manifest is checked as +/// a module's is, and the script is parsed, not run. +pub(crate) fn read_bundle(bytes: &[u8]) -> Result<(Manifest, Script)> { + let mut map: Map = serde_json::from_slice(bytes).map_err(|e| Error::Manifest(e.to_string()))?; + if !is_js(&map) { + return Err(Error::Manifest(NOT_JS.into())); + } + let named = map.remove("script"); + let source = match map.remove("source") { + Some(Value::String(s)) => s, + Some(_) => return Err(Error::Manifest(SOURCE_RULE.into())), + None if named.is_some() => return Err(Error::Manifest(SOURCE_RULE.into())), + None => return Err(no_script()), + }; + let name = named.as_ref().map_or_else(|| Ok(DEFAULT_SCRIPT.to_string()), script_name)?; + if source.len() > MAX_SCRIPT_BYTES { + return Err(Error::Module(format!("{} is {} bytes (limit {})", name, source.len(), MAX_SCRIPT_BYTES))); + } + let manifest = serde_json::to_vec(&map).map_err(|e| Error::Manifest(e.to_string()))?; + let manifest = Manifest::parse(&manifest)?; + if let Err(e) = vectorcraft_js::parse(&source, &options()) { + let named = Named { id: &manifest.id, script: &name }; + return Err(Error::Module(located(&permissions::display_text(&e.message, MAX_ERROR_TEXT), &named, Some((e.line, e.column))))); + } + Ok((manifest, Script { name, source })) +} + +/// `reason` followed by where it happened: the plug-in's id, its script's name and, when `at` gives +/// them, the line and column. +fn located(reason: &str, named: &Named<'_>, at: Option<(u32, u32)>) -> String { + let (id, script) = (named.id, named.script); + match at { + Some((line, column)) if line > 0 => format!("{reason} ({id}, {script} line {line}, column {column})"), + _ => format!("{reason} ({id}, {script})"), + } +} + +/// One run's input and budgets. +pub(crate) struct Call<'a> { + pub(crate) input: &'a [u8], + pub(crate) params: &'a [u8], + pub(crate) limits: &'a Limits, + /// The plug-in's memory cap, which the run's heap stays within. + pub(crate) max_memory: usize, + pub(crate) deadline: Deadline, +} + +/// The heap a run may use with memory cap `max_memory`. +fn heap_bytes(max_memory: usize) -> usize { + vectorcraft_js::Limits::default().heap_bytes.min(max_memory) +} + +/// Runs `script`, the code of the plug-in `m` describes, on `call`'s input in a fresh realm → the +/// output JSON. What it reported with `vc.progress` and `vc.log` goes to `report`. +pub(crate) fn run(script: &Script, m: &Manifest, call: &Call<'_>, state: Run, report: &mut Report) -> Result> { + let heap = heap_bytes(call.max_memory); + // Each UTF-8 byte may become a UTF-16 code unit of two bytes, and the parsed JSON takes more. + if call.input.len().saturating_add(call.params.len()) > heap / 8 { + return Err(Error::Limit(SELECTION_TOO_LARGE.into())); + } + // The host writes the input and the parameters with serde_json, so they are UTF-8. + let (input, params) = (String::from_utf8_lossy(call.input), String::from_utf8_lossy(call.params)); + let state = Rc::new(RefCell::new(state)); + let out = run_realm(script, m, (&*input, &*params), call, heap, &state); + *report = std::mem::take(&mut state.borrow_mut().report); + out +} + +/// What errors name: the plug-in's id and its script's file name. +struct Named<'a> { + id: &'a str, + script: &'a str, +} + +fn run_realm( + script: &Script, + m: &Manifest, + (input, params): (&str, &str), + call: &Call<'_>, + heap: usize, + state: &Rc>, +) -> Result> { + let defaults = vectorcraft_js::Limits::default(); + let fuel = call.limits.fuel_base.saturating_add((call.input.len() as u64).saturating_mul(call.limits.fuel_per_byte)); + let limits = vectorcraft_js::Limits { fuel, heap_bytes: heap, ..defaults }; + let mut realm = Realm::with_options(options(), limits); + realm.set_clock(|| f64::NAN); + let named = Named { id: &m.id, script: &script.name }; + realm.define_host_object("vc", vc_items(input, params, m, state)).map_err(|e| match e.kind { + RunErrorKind::Limit(LimitKind::Heap) => Error::Limit(SELECTION_TOO_LARGE.into()), + _ => js_error(&realm, e, vectorcraft_js::UNKNOWN_SOURCE, &named), + })?; + let (_, tag) = drive(&mut realm, &script.source, &call.deadline, &named, None)?; + // The call takes what the top level left of the budget. + let left = realm.fuel_left(); + realm.set_limits(vectorcraft_js::Limits { fuel: left, ..realm.limits().clone() }); + let (value, _) = drive(&mut realm, ENTRY, &call.deadline, &named, Some(tag))?; + vectorcraft_doc::cancel::check().map_err(|_| Error::Cancelled)?; + call.deadline.check()?; + match value { + JsValue::String(s) if s.len() > call.limits.max_output_bytes => { + let (what, len, max) = ("the output", s.len(), call.limits.max_output_bytes); + Err(Error::Limit(format!("output size ({what} is {len} bytes, limit {max})"))) + } + JsValue::String(s) => Ok(s.into_bytes()), + _ => Err(Error::Output(located(NO_OUTPUT, &named, None))), + } +} + +/// The error of a `run` that returned nothing JSON can write. +const NO_OUTPUT: &str = "run(input, params) returned no output object"; + +/// The limit a run that nested its calls too deeply exceeded. +const CALL_DEPTH: &str = "call depth"; + +/// Runs `source` in `realm` to its end, in slices of [`FUEL_SLICE`] with the deadline and Cancel +/// checked between them → its completion value, and the source tag of the plug-in's script: +/// `script_tag`, or with `None` the tag of `source`, which is then the script. +fn drive(realm: &mut Realm, source: &str, deadline: &Deadline, named: &Named<'_>, script_tag: Option) -> Result<(JsValue, u32)> { + let started = realm.start(source); + let tag = script_tag.unwrap_or_else(|| realm.script_tag()); + started.map_err(|e| js_error(realm, e, tag, named))?; + loop { + match realm.advance(FUEL_SLICE) { + Ok(Progress::Done(v)) => return Ok((v, tag)), + Ok(Progress::Paused) => {} + Err(e) => return Err(js_error(realm, e, tag, named)), + } + if vectorcraft_doc::cancel::check().is_err() { + realm.end(); + return Err(Error::Cancelled); + } + if let Err(e) = deadline.check() { + realm.end(); + return Err(e); + } + } +} + +/// The plug-in error for `e`, which a run of `realm` ended with: it names the plug-in and the script, +/// and the line and column when the error is in the script (source tag `tag`). +fn js_error(realm: &Realm, e: RunError, tag: u32, named: &Named<'_>) -> Error { + let at = (realm.error_tag() == tag).then_some((e.line, e.column)); + let message = permissions::display_text(&e.message, MAX_ERROR_TEXT); + match e.kind { + RunErrorKind::Syntax => Error::Module(located(&message, named, at)), + RunErrorKind::Thrown | RunErrorKind::Limit(LimitKind::Host) => Error::Failed(located(&message, named, at)), + RunErrorKind::Limit(LimitKind::Fuel | LimitKind::Unbroken) => Error::Limit(located("instruction budget", named, at)), + RunErrorKind::Limit(LimitKind::Heap) => Error::Limit(located("memory budget", named, at)), + RunErrorKind::Limit(LimitKind::Frames | LimitKind::Reentry) => Error::Limit(located(CALL_DEPTH, named, at)), + RunErrorKind::Limit(LimitKind::Interrupted) => Error::Cancelled, + RunErrorKind::Internal => Error::Trap(located(&message, named, at)), + } +} + +/// The members of the realm's `vc` object. +fn vc_items(input: &str, params: &str, m: &Manifest, state: &Rc>) -> Vec<(String, HostItem)> { + let mut items = vec![ + ("input".to_string(), HostItem::Value(Data::String(input.into()))), + ("params".to_string(), HostItem::Value(Data::String(params.into()))), + ]; + if !m.permissions().contains(&Permission::Progress) { + return items; + } + let number = |args: &[Data], i: usize, rule: &str| match args.get(i) { + Some(Data::Number(n)) => Ok(*n), + _ => Err(HostError::Type(rule.into())), + }; + let run = state.clone(); + items.push(( + "progress".into(), + HostItem::Function(Rc::new(move |args| { + let (done, total) = (number(&args, 0, PROGRESS_ARGS)?, number(&args, 1, PROGRESS_ARGS)?); + // `as` turns NaN into 0 and clamps the rest, as `vc_progress` clamps negative values. + run.borrow_mut().progress(done as i64, total as i64); + Ok(Data::Undefined) + })), + )); + let run = state.clone(); + items.push(("cancelled".into(), HostItem::Function(Rc::new(move |_| Ok(Data::Bool(run.borrow().cancelled() == 1)))))); + let run = state.clone(); + items.push(( + "log".into(), + HostItem::Function(Rc::new(move |args| { + let level = number(&args, 0, LOG_ARGS)?; + let Some(Data::String(text)) = args.get(1) else { return Err(HostError::Type(LOG_ARGS.into())) }; + let level = if level.fract() == 0.0 && (0.0..=3.0).contains(&level) { level as i32 } else { LOG_BAD_LEVEL }; + match run.borrow_mut().log(level, text.as_bytes(), 0, text.len()) { + LOG_WRITTEN => Ok(Data::Bool(true)), + LOG_DROPPED => Ok(Data::Bool(false)), + _ => Err(HostError::Range(LOG_ARGS.into())), + } + })), + )); + items +} + +#[cfg(test)] +mod tests { + use serde_json::{Value, json}; + + use crate::{Error, Limits, Plugin}; + + /// A JavaScript filter `id` with `source` as its code, and `extra` manifest keys. + fn bundle(id: &str, source: &str, extra: Value) -> Vec { + let mut m = json!({"id": id, "name": "JS test", "kind": "filter", "runtime": "js", "script": "test.js", "source": source}); + if let (Some(m), Value::Object(extra)) = (m.as_object_mut(), extra) { + m.extend(extra); + } + serde_json::to_vec(&m).unwrap() + } + + fn load(bytes: &[u8]) -> crate::Result { + load_with(bytes, Limits::default()) + } + + fn load_with(bytes: &[u8], limits: Limits) -> crate::Result { + let _lock = crate::safe_mode::TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner()); + Plugin::load(bytes, limits) + } + + const PATH: &str = r#"{"objects":[{"id":7,"type":"path","fills":[{"type":"solid","color":{"model":"rgb","r":1,"g":0,"b":0}}]}]}"#; + + /// The output of `run(input, params)` is the run's output JSON. + #[test] + fn a_filter_returns_its_objects_as_json() { + let src = "function run(input, params) { return {objects: input.objects.map(function (o) { \ + return {id: o.id, fills: [{type: 'solid', color: {model: 'rgb', r: 0, g: 0, b: params.blue}}]}; })}; }"; + let p = load(&bundle("test.js.blue", src, json!({}))).unwrap(); + assert_eq!((p.runtime(), p.script()), (crate::Runtime::Js, Some("test.js"))); + let out: Value = serde_json::from_slice(&p.run(PATH.as_bytes(), br#"{"blue":1}"#).unwrap()).unwrap(); + assert_eq!(out, json!({"objects": [{"id": 7, "fills": [{"type": "solid", "color": {"model": "rgb", "r": 0, "g": 0, "b": 1}}]}]})); + } + + /// The realm has none of the script runner's globals, so code that reads them throws a + /// `ReferenceError` naming the global, the plug-in and where in its script. + #[test] + fn file_folder_and_app_are_not_defined() { + for name in ["File", "Folder", "$", "app", "BridgeTalk"] { + let src = format!("function run(input) {{\n return {name}.x;\n}}"); + let e = load(&bundle("test.js.globals", &src, json!({}))).unwrap().run(PATH.as_bytes(), b"{}").unwrap_err(); + let Error::Failed(why) = &e else { panic!("{name}: {e:?}") }; + assert!(why.starts_with("ReferenceError") && why.contains(name), "{name}: {why}"); + assert!(why.ends_with("(test.js.globals, test.js line 2, column 10)"), "{name}: {why}"); + } + let p = load(&bundle("test.js.clock", "function run() { return {objects: [], n: String(Date.now())}; }", json!({}))).unwrap(); + let out: Value = serde_json::from_slice(&p.run(b"{\"objects\":[]}", b"{}").unwrap()).unwrap(); + assert_eq!(out["n"], "NaN", "no clock"); + } + + /// Each run has a realm of its own: what one run changes in the built-ins, the next run doesn't + /// see. + #[test] + fn a_polluted_prototype_does_not_reach_the_next_run() { + let src = "function run() { var seen = Object.prototype.polluted; Object.prototype.polluted = 1; \ + Array.prototype.map = null; return {objects: [], seen: String(seen)}; }"; + let p = load(&bundle("test.js.pollute", src, json!({}))).unwrap(); + for _ in 0..2 { + let out: Value = serde_json::from_slice(&p.run(b"{\"objects\":[]}", b"{}").unwrap()).unwrap(); + assert_eq!(out["seen"], "undefined"); + } + } + + /// An endless loop ends with the instruction budget, naming the plug-in and the line. + #[test] + fn an_endless_loop_ends_with_the_instruction_budget() { + let p = load(&bundle("test.js.loop", "function run() {\n for (;;) {}\n}", json!({}))).unwrap(); + let limits = Limits { fuel_base: 3 * super::FUEL_SLICE, fuel_per_byte: 0, ..Limits::default() }; + let e = p.run_limited(b"{\"objects\":[]}", b"{}", &limits).unwrap_err(); + assert!(matches!(&e, Error::Limit(why) if why.starts_with("instruction budget (test.js.loop, test.js line 2")), "{e:?}"); + } + + /// A plug-in that fills its heap ends with its memory budget, and a realm another caller holds + /// meanwhile, such as a script's, runs on as before. + #[test] + fn heap_exhaustion_leaves_a_held_realm_usable() { + let mut held = vectorcraft_js::Realm::new(); + held.run("var kept = 41;").unwrap(); + let src = "function run() { var a = []; for (;;) { a.push(new Array(1000).join('x') + a.length); } }"; + let small = load_with(&bundle("test.js.heap", src, json!({})), Limits { max_memory_bytes: 8 << 20, ..Limits::default() }).unwrap(); + let e = small.run(b"{\"objects\":[]}", b"{}").unwrap_err(); + assert!(matches!(&e, Error::Limit(why) if why.starts_with("memory budget (test.js.heap")), "{e:?}"); + assert_eq!(held.run("kept + 1").unwrap(), vectorcraft_js::JsValue::Number(42.0)); + } + + /// An input too large for the heap is refused before it is copied in. + #[test] + fn a_selection_too_large_for_the_heap_is_refused() { + let small = + load_with(&bundle("test.js.big", "function run(i) { return i; }", json!({})), Limits { max_memory_bytes: 1 << 20, ..Limits::default() }) + .unwrap(); + let input = format!(r#"{{"objects":[],"pad":"{}"}}"#, "x".repeat(200_000)); + assert_eq!(small.run(input.as_bytes(), b"{}"), Err(Error::Limit(crate::runtime::SELECTION_TOO_LARGE.into()))); + } + + /// A result that isn't an output object, and a script without `run`, fail the run. + #[test] + fn a_missing_entry_or_result_fails_the_run() { + let e = load(&bundle("test.js.none", "var x = 1;", json!({}))).unwrap().run(b"{\"objects\":[]}", b"{}").unwrap_err(); + assert!(matches!(&e, Error::Failed(why) if why.contains("defines no function run")), "{e:?}"); + let e = load(&bundle("test.js.undef", "function run() {}", json!({}))).unwrap().run(b"{\"objects\":[]}", b"{}").unwrap_err(); + assert!(matches!(&e, Error::Output(why) if why.contains("test.js.undef")), "{e:?}"); + let e = load(&bundle("test.js.cycle", "function run() { var o = {}; o.o = o; return o; }", json!({}))) + .unwrap() + .run(b"{\"objects\":[]}", b"{}") + .unwrap_err(); + assert!(matches!(&e, Error::Failed(why) if why.starts_with("TypeError")), "{e:?}"); + } + + /// With `progress`, `vc.progress` and `vc.log` report as their imports do; without it, `vc` + /// has neither. + #[test] + fn progress_and_log_need_the_progress_permission() { + let src = "function run() { vc.progress(3, 4); vc.log(2, 'half'); return {objects: [], cancelled: vc.cancelled()}; }"; + let p = load(&bundle("test.js.progress", src, json!({"api": 2, "permissions": ["progress"]}))).unwrap(); + let (out, report) = p.run_reporting(b"{\"objects\":[]}", b"{}", p.limits()); + let out: Value = serde_json::from_slice(&out.unwrap()).unwrap(); + assert_eq!(out["cancelled"], false); + assert_eq!(report.progress, Some((3, 4))); + assert_eq!(report.lines, vec![crate::LogLine { level: crate::LogLevel::Info, text: "half".into() }]); + let e = load(&bundle("test.js.quiet", src, json!({}))).unwrap().run(b"{\"objects\":[]}", b"{}").unwrap_err(); + assert!(matches!(&e, Error::Failed(why) if why.starts_with("TypeError")), "{e:?}"); + } + + /// Loading checks the manifest and the script, and runs none of it. + #[test] + fn loading_refuses_a_bad_manifest_or_script() { + let ok = "function run() { return {objects: []}; }"; + let refused = |bytes: Vec| load(&bytes).unwrap_err(); + let e = refused(bundle("test.js.syntax", "function run( {", json!({}))); + assert!(matches!(&e, Error::Module(why) if why.contains("(test.js.syntax, test.js line 1, column")), "{e:?}"); + let big = "x".repeat(super::MAX_SCRIPT_BYTES + 1); + assert!(matches!(refused(bundle("test.js.big", &big, json!({}))), Error::Module(why) if why.starts_with("test.js is"))); + let e = refused(bundle("test.js.effect", ok, json!({"kind": "effect"}))); + assert!(matches!(&e, Error::Manifest(why) if why.contains("`runtime` \"js\" is for an object filter")), "{e:?}"); + let e = refused(bundle("test.js.settings", ok, json!({"api": 2, "permissions": ["settings"]}))); + assert!(matches!(&e, Error::Manifest(why) if why.contains("`settings`")), "{e:?}"); + let e = refused(bundle("test.js.name", ok, json!({"script": "../x.js"}))); + assert!(matches!(&e, Error::Manifest(why) if why.starts_with("`script`")), "{e:?}"); + let e = refused(bundle("test.js.py", ok, json!({"runtime": "py"}))); + assert!(matches!(&e, Error::Manifest(why) if why == super::NOT_JS), "{e:?}"); + let mut no_source: Value = serde_json::from_slice(&bundle("test.js.nosource", ok, json!({}))).unwrap(); + no_source.as_object_mut().unwrap().remove("source"); + let e = refused(serde_json::to_vec(&no_source).unwrap()); + assert!(matches!(&e, Error::Manifest(why) if why.contains("`source`")), "{e:?}"); + // Top-level code that would throw does not run at load. + assert!(load(&bundle("test.js.lazy", "throw new Error('ran');", json!({}))).is_ok()); + } + + /// A WebAssembly module's manifest can't give `"runtime": "js"`. + #[test] + fn a_module_manifest_cannot_be_javascript() { + let manifest = r#"{"id":"test.js.wasm","name":"T","kind":"filter","runtime":"js"}"#; + let bytes = wat::parse_str(crate::wat::returning(manifest, r#"{"objects":[]}"#)).unwrap(); + assert!(matches!(load(&bytes), Err(Error::Manifest(why)) if why.contains("`runtime`"))); + } + + /// The SHA-256 a grant records is the bundle's, so another script is another module. + #[test] + fn the_hash_covers_the_script() { + let a = load(&bundle("test.js.hash", "function run() { return {objects: []}; }", json!({}))).unwrap(); + let b = load(&bundle("test.js.hash", "function run() { return {objects: [] }; }", json!({}))).unwrap(); + assert_ne!(a.hash(), b.hash()); + } + + #[test] + fn script_names_stay_in_the_manifest_s_folder() { + for ok in ["tint.js", "Tint Tool.JS", "a.b.js"] { + assert!(super::valid_script_name(ok), "{ok}"); + } + for bad in ["", ".js", ".hidden.js", "../x.js", "sub/x.js", "sub\\x.js", "c:x.js", "x.jsx", "x.js\n", "x.wasm"] { + assert!(!super::valid_script_name(bad), "{bad:?}"); + } + assert!(!super::valid_script_name(&format!("{}.js", "a".repeat(126)))); + } +} diff --git a/crates/plugins/src/lib.rs b/crates/plugins/src/lib.rs index 019dd0d858..4e244b46eb 100644 --- a/crates/plugins/src/lib.rs +++ b/crates/plugins/src/lib.rs @@ -32,6 +32,10 @@ //! the set of [`permissions`] its manifest lists, which the user approves when it is installed. A //! filter or a live effect may also add menu commands of its own ([`Command`]), which the host //! runs through `vc_run` with the command's id in `_context`. +//! +//! An object filter may also be written in JavaScript ([`js`]): its manifest gives +//! `"runtime": "js"` and names a `.js` file, which runs in a fresh `vectorcraft-js` realm for each +//! run, with the same input, output, permissions and budgets. #![forbid(unsafe_code)] pub mod deferred; @@ -40,6 +44,7 @@ pub mod effect; pub mod export; pub mod host; pub mod import; +pub mod js; pub mod manifest; pub mod objects; pub mod painted; @@ -52,7 +57,7 @@ pub mod wat; pub use dialog::ParamUi; pub use host::{LogLevel, LogLine, Report}; -pub use manifest::{Budget, Command, InputKind, Kind, Manifest, Param, ParamSpec}; +pub use manifest::{Budget, Command, InputKind, Kind, Manifest, Param, ParamSpec, Runtime}; pub use runtime::{ABI_VERSION, HEAVY_FUEL, HEAVY_WALL_TIME_MS, LARGE_FUEL, Limits, Plugin, heavy_terms}; #[doc(hidden)] pub use runtime::{BYTES_COPIED_PER_FUEL, FUEL_SLICE}; diff --git a/crates/plugins/src/manifest.rs b/crates/plugins/src/manifest.rs index b6e17e3ad0..a6ae63a9bb 100644 --- a/crates/plugins/src/manifest.rs +++ b/crates/plugins/src/manifest.rs @@ -114,6 +114,32 @@ impl Budget { } } +/// What runs a plug-in's code. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub enum Runtime { + /// A WebAssembly module ([`crate::Plugin::load`]); the manifest is the module's `vc_manifest`. + #[default] + Wasm, + /// A JavaScript file run on `vectorcraft-js` ([`crate::js`]): an object filter whose manifest + /// gives `"runtime": "js"`. + Js, +} + +impl Runtime { + pub fn name(self) -> &'static str { + match self { + Runtime::Wasm => "wasm", + Runtime::Js => "js", + } + } + + /// WebAssembly, which a manifest written back leaves out (`skip_serializing_if`). + fn is_wasm(&self) -> bool { + *self == Runtime::Wasm + } +} + /// One declared parameter. #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] #[serde(tag = "type", rename_all = "camelCase")] @@ -348,6 +374,9 @@ pub struct Manifest { /// lists any ([`Manifest::validate`]). #[serde(default, skip_serializing_if = "Vec::is_empty")] pub command_allowlist: Vec, + /// What runs its code: WebAssembly when left out, or `"js"` for a JavaScript filter. + #[serde(default, skip_serializing_if = "Runtime::is_wasm")] + pub runtime: Runtime, } impl Manifest { @@ -383,6 +412,7 @@ impl Manifest { paint_output: false, commands: Vec::new(), command_allowlist: Vec::new(), + runtime: Runtime::Wasm, } } @@ -440,7 +470,30 @@ impl Manifest { } self.validate_params()?; self.validate_commands()?; - self.validate_allowlist() + self.validate_allowlist()?; + self.validate_runtime() + } + + /// A JavaScript plug-in (`"runtime": "js"`) is an object filter, and of the host's permissions + /// it lists only `progress`: its realm has no settings, cache or command calls. + fn validate_runtime(&self) -> Result<()> { + if self.runtime == Runtime::Wasm { + return Ok(()); + } + if self.kind != Kind::Filter { + let kind = self.kind.name(); + return Err(Error::Manifest(format!("`runtime` \"js\" is for an object filter (`kind` \"filter\"), not `kind` \"{kind}\""))); + } + let listed = self.permissions.as_deref().unwrap_or_default(); + for p in [Permission::Settings, Permission::Cache, Permission::Commands] { + if listed.iter().any(|n| n == p.name()) { + let name = p.name(); + return Err(Error::Manifest(format!( + "a JavaScript plug-in can't list the permission `{name}`: of the host's permissions it may list `progress`" + ))); + } + } + Ok(()) } /// `commandAllowlist` lists at most [`MAX_ALLOWED_COMMANDS`] distinct command ids diff --git a/crates/plugins/src/registry.rs b/crates/plugins/src/registry.rs index 6d20452ce6..01a1f7731e 100644 --- a/crates/plugins/src/registry.rs +++ b/crates/plugins/src/registry.rs @@ -178,14 +178,64 @@ pub fn intern(s: &str) -> &'static str { v } -/// Reads a `.wasm` file (refusing anything that isn't a regular file or exceeds the module limit) +/// Reads a `.wasm` file (refusing anything that isn't a regular file or exceeds the module limit), +/// or a JavaScript plug-in's `.vcplugin` manifest and the script it names ([`read_js_package`]), /// and loads it. #[cfg(not(target_arch = "wasm32"))] pub fn load_file(path: &std::path::Path, limits: Limits) -> Result { - let bytes = read_module(path, &limits, || {})?; + load_file_where(path, limits, &|_| Ok(())) +} + +/// [`load_file`], reading a JavaScript plug-in's script only when `allow` accepts its path. +#[cfg(not(target_arch = "wasm32"))] +fn load_file_where(path: &std::path::Path, limits: Limits, allow: &dyn Fn(&std::path::Path) -> std::result::Result<(), String>) -> Result { + let bytes = if is_js_package(path) { read_js_package(path, allow)? } else { read_module(path, &limits, || {})? }; Ok(Plugin::load(&bytes, limits)?.with_source(path.display().to_string())) } +/// Does `path` name a JavaScript plug-in's manifest file: is its extension `.vcplugin`? +pub fn is_js_package(path: &std::path::Path) -> bool { + path.extension().is_some_and(|x| x.eq_ignore_ascii_case(crate::js::PACKAGE_EXT)) +} + +/// The JavaScript plug-in whose manifest file is `path`, as the one JSON object [`Plugin::load`] +/// reads: the manifest, with the text of the script its `script` names in `source`. The manifest +/// file must give `"runtime": "js"` and `script`, a `.js` file in the same folder, and no `source`. +/// Each file is refused before it is read when it isn't a regular file or is larger than its limit +/// ([`crate::manifest::MAX_MANIFEST_BYTES`], [`crate::js::MAX_SCRIPT_BYTES`]); the script is read +/// only when `allow` accepts its path, and must be UTF-8. +#[cfg(not(target_arch = "wasm32"))] +pub fn read_js_package(path: &std::path::Path, allow: &dyn Fn(&std::path::Path) -> std::result::Result<(), String>) -> Result> { + read_js_package_with(path, allow, || {}) +} + +/// [`read_js_package`], with `opening` run between the script's size check and its open. +#[cfg(not(target_arch = "wasm32"))] +fn read_js_package_with( + path: &std::path::Path, + allow: &dyn Fn(&std::path::Path) -> std::result::Result<(), String>, + opening: impl FnOnce(), +) -> Result> { + use serde_json::Value; + let manifest_limits = Limits { max_module_bytes: crate::manifest::MAX_MANIFEST_BYTES, ..Limits::default() }; + let bytes = read_module(path, &manifest_limits, || {})?; + let mut map: serde_json::Map = serde_json::from_slice(&bytes).map_err(|e| Error::Manifest(format!("{}: {e}", path.display())))?; + if !crate::js::is_js(&map) { + return Err(Error::Manifest(crate::js::NOT_JS.into())); + } + if map.contains_key("source") { + return Err(Error::Manifest(crate::js::SOURCE_RULE.into())); + } + let name = crate::js::script_name(map.get("script").ok_or_else(crate::js::no_script)?)?; + let file = path.parent().unwrap_or(std::path::Path::new("")).join(&name); + allow(&file).map_err(Error::Io)?; + let script_limits = Limits { max_module_bytes: crate::js::MAX_SCRIPT_BYTES, ..Limits::default() }; + let source = read_module(&file, &script_limits, opening)?; + let source = String::from_utf8(source).map_err(|_| Error::Module("the script is not UTF-8 text".into()))?; + map.insert("source".into(), Value::String(source)); + serde_json::to_vec(&map).map_err(|e| Error::Manifest(e.to_string())) +} + /// The bytes of the module file at `path`. A path that doesn't name a regular file is refused /// before it is opened, and so is one over the module limit. On Unix the file is opened without /// waiting, so a named pipe put in its place after that check doesn't hold the load until something @@ -228,7 +278,7 @@ fn open_module(path: &std::path::Path) -> std::io::Result { #[cfg(not(target_arch = "wasm32"))] const MAX_FOLDER_FILES: usize = 1000; -/// The first [`MAX_FOLDER_FILES`] `*.wasm` paths directly in `dir` by file name, sorted, and how +/// The first [`MAX_FOLDER_FILES`] `*.wasm` and `*.vcplugin` paths directly in `dir` by file name, sorted, and how /// many more there are. Only that many paths are held while the folder is listed. An error while /// the folder is listed is returned, as one opening it is. #[cfg(not(target_arch = "wasm32"))] @@ -239,7 +289,7 @@ fn folder_files(dir: &std::path::Path) -> Result<(Vec, usize let mut more = 0; for entry in rd { let p = entry.map_err(io)?.path(); - if !p.extension().is_some_and(|x| x.eq_ignore_ascii_case("wasm")) { + if !p.extension().is_some_and(|x| x.eq_ignore_ascii_case("wasm")) && !is_js_package(&p) { continue; } kept.push(p); @@ -269,7 +319,7 @@ pub struct FolderReport { pub disabled_changed: bool, } -/// Installs every `*.wasm` directly in `dir` (not recursive), in file-name order, up to the first +/// Installs every `*.wasm` and `*.vcplugin` ([`read_js_package`]) directly in `dir` (not recursive), in file-name order, up to the first /// 1,000 by file name; the report counts the files left out ([`FolderReport::left_out`]). Anything /// that isn't a regular file, such as a named pipe, is reported and skipped without waiting on it /// ([`load_file`]). A bad module is reported and skipped, the others still load; so is a heavy one @@ -280,7 +330,7 @@ pub fn load_folder(dir: &std::path::Path) -> Result { load_folder_where(dir, |_| Ok(()), approved) } -/// [`load_folder`], loading only the files `allow` accepts, and of the plug-ins that list +/// [`load_folder`], loading only the files `allow` accepts (a JavaScript plug-in's script too), and of the plug-ins that list /// permissions only those `approve` accepts and a recorded grant covers ([`install`]); the others /// are reported as failed with the reason. A plug-in the user disabled ([`crate::safe_mode::skipped`]) is reported and /// skipped, by its file before it loads or by its id after (its file is then disabled too, so the @@ -309,7 +359,7 @@ pub fn load_folder_where( continue; } let token = safe_mode::loading(&item); - let loaded = load_file(&f, Limits::default()); + let loaded = load_file_where(&f, Limits::default(), &allow); safe_mode::loaded(token); match loaded { Ok(p) if safe_mode::skipped(&Item::of(&p)) => { @@ -578,6 +628,82 @@ mod tests { assert!(matches!(&read, Err(Error::Module(e)) if e.contains("limit 16")), "{read:?}"); } + /// A JavaScript plug-in's manifest file and its script, in `dir`. + #[cfg(not(target_arch = "wasm32"))] + fn write_js(dir: &std::path::Path, id: &str, manifest: serde_json::Value, script: Option<&str>) -> std::path::PathBuf { + let mut m = serde_json::json!({"id": id, "name": "JS", "kind": "filter", "runtime": "js", "script": "f.js"}); + if let (Some(m), serde_json::Value::Object(extra)) = (m.as_object_mut(), manifest) { + m.extend(extra); + } + let path = dir.join(format!("{id}.vcplugin")); + std::fs::write(&path, serde_json::to_vec(&m).unwrap()).unwrap(); + if let Some(script) = script { + std::fs::write(dir.join("f.js"), script).unwrap(); + } + path + } + + /// A `.vcplugin` in a folder installs with its script, and its SHA-256 is the one an install of + /// the same package by bytes gets. + #[cfg(not(target_arch = "wasm32"))] + #[test] + fn a_folder_installs_a_javascript_plugin() { + let _lock = crate::safe_mode::TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner()); + crate::safe_mode::set_active(None); + let dir = test_dir("js"); + let id = "test.registry.js"; + write_js(&dir, id, serde_json::json!({}), Some("function run(i) { return i; }")); + let r = load_folder_where(&dir, |_| Ok(()), |_| false).unwrap(); + let bytes = read_js_package(&dir.join(format!("{id}.vcplugin")), &|_| Ok(())).unwrap(); + std::fs::remove_dir_all(&dir).unwrap(); + assert_eq!(r.loaded, vec![id.to_string()], "{r:?}"); + let p = get(id).unwrap(); + assert_eq!((p.script(), p.hash()), (Some("f.js"), crate::permissions::sha256_hex(&bytes).as_str())); + assert!(remove(id)); + } + + /// A manifest with `"runtime": "js"` and no `script` is refused, and the error names the key; + /// so is one that names a script `allow` refuses or that isn't there. + #[cfg(not(target_arch = "wasm32"))] + #[test] + fn a_javascript_manifest_needs_its_script() { + let dir = test_dir("js-script"); + let no_key = write_js(&dir, "a", serde_json::json!({"script": null}), None); + let mut m: serde_json::Value = serde_json::from_slice(&std::fs::read(&no_key).unwrap()).unwrap(); + m.as_object_mut().unwrap().remove("script"); + std::fs::write(&no_key, serde_json::to_vec(&m).unwrap()).unwrap(); + let missing = write_js(&dir, "b", serde_json::json!({}), None); + let inline = write_js(&dir, "c", serde_json::json!({"source": "function run(i) { return i; }"}), None); + let not_js = write_js(&dir, "d", serde_json::json!({"runtime": "wasm"}), None); + let refused = read_js_package(&missing, &|p| Err(format!("{} is outside", p.display()))); + let results = [ + read_js_package(&no_key, &|_| Ok(())), + read_js_package(&missing, &|_| Ok(())), + read_js_package(&inline, &|_| Ok(())), + read_js_package(¬_js, &|_| Ok(())), + ]; + std::fs::remove_dir_all(&dir).unwrap(); + assert!(matches!(&results[0], Err(Error::Manifest(e)) if e.starts_with("`runtime` \"js\" needs `script`")), "{:?}", results[0]); + assert!(matches!(&results[1], Err(Error::Io(e)) if e.contains("f.js")), "{:?}", results[1]); + assert!(matches!(&results[2], Err(Error::Manifest(e)) if e.contains("`source`")), "{:?}", results[2]); + assert!(matches!(&results[3], Err(Error::Manifest(e)) if e == crate::js::NOT_JS), "{:?}", results[3]); + assert!(matches!(&refused, Err(Error::Io(e)) if e.ends_with("is outside")), "{refused:?}"); + } + + /// A script larger than the limit is refused by its size before it is opened. + #[cfg(not(target_arch = "wasm32"))] + #[test] + fn an_oversized_script_is_refused_before_it_is_read() { + let dir = test_dir("js-big"); + let path = write_js(&dir, "big", serde_json::json!({}), Some("")); + std::fs::File::options().write(true).open(dir.join("f.js")).unwrap().set_len(crate::js::MAX_SCRIPT_BYTES as u64 + 1).unwrap(); + let opened = std::cell::Cell::new(false); + let read = read_js_package_with(&path, &|_| Ok(()), || opened.set(true)); + std::fs::remove_dir_all(&dir).unwrap(); + assert!(matches!(&read, Err(Error::Module(e)) if e.contains(&format!("limit {}", crate::js::MAX_SCRIPT_BYTES))), "{read:?}"); + assert!(!opened.get(), "the script was opened"); + } + /// A folder load reports a subfolder, a named pipe and a link to a named pipe with `.wasm` /// names as not files, and goes on. #[cfg(unix)] diff --git a/crates/plugins/src/runtime.rs b/crates/plugins/src/runtime.rs index 7c4262dd4e..dc52690adf 100644 --- a/crates/plugins/src/runtime.rs +++ b/crates/plugins/src/runtime.rs @@ -7,7 +7,7 @@ use wasmi::{ use wasmparser::{Validator, WasmFeatures}; use crate::host::{self, Bridge, Deadline, Host, Report, Run}; -use crate::manifest::{MAX_MANIFEST_BYTES, Manifest}; +use crate::manifest::{MAX_MANIFEST_BYTES, Manifest, Runtime}; use crate::permissions::Permission; use crate::{Error, Kind, Result}; @@ -135,12 +135,17 @@ impl Default for Limits { } } +/// A plug-in's code: a WebAssembly module, or a JavaScript file ([`crate::js`]). +enum Code { + Wasm { engine: Engine, module: Module }, + Js(crate::js::Script), +} + /// A loaded, validated plug-in. Cheap to share (`Arc`) and safe to run from several threads: -/// every run gets its own store and instance. +/// every run gets its own store and instance, or for a JavaScript plug-in its own realm. pub struct Plugin { manifest: Manifest, - engine: Engine, - module: Module, + code: Code, limits: Limits, size: usize, hash: String, @@ -222,12 +227,21 @@ type RunArgs = (i32, i32, i32, i32); impl Plugin { /// Validates and loads a module: checks the ABI version, the exports and reads the manifest, and /// checks that each host import it asks for is one the host offers ([`crate::host::IMPORTS`]) - /// and its manifest allows. In Safe Mode nothing is loaded ([`Error::SafeMode`]). + /// and its manifest allows. Bytes that hold a JSON object with `"runtime": "js"` are a + /// JavaScript plug-in ([`crate::js`]): its manifest is checked and its script parsed, and none + /// of it runs. In Safe Mode nothing is loaded ([`Error::SafeMode`]). pub fn load(bytes: &[u8], limits: Limits) -> Result { crate::safe_mode::check()?; if bytes.len() > limits.max_module_bytes { return Err(Error::Module(format!("module is {} bytes (limit {})", bytes.len(), limits.max_module_bytes))); } + if bytes.trim_ascii_start().starts_with(b"{") { + let (manifest, script) = crate::js::read_bundle(bytes)?; + let hash = crate::permissions::sha256_hex(bytes); + let mut p = Plugin { manifest, code: Code::Js(script), limits, size: bytes.len(), hash, source: None, serial: 0 }; + p.heavy_limits(); + return Ok(p); + } if !bytes.starts_with(b"\0asm") { return Err(Error::Module("not a WebAssembly binary (missing \\0asm header)".into())); } @@ -242,7 +256,15 @@ impl Plugin { let module = Module::new(&engine, bytes).map_err(|e| Error::Module(e.to_string()))?; let imports = host::check_imports(&module)?; let hash = crate::permissions::sha256_hex(bytes); - let mut p = Plugin { manifest: Manifest::placeholder(), engine, module, limits, size: bytes.len(), hash, source: None, serial: 0 }; + let mut p = Plugin { + manifest: Manifest::placeholder(), + code: Code::Wasm { engine, module }, + limits, + size: bytes.len(), + hash, + source: None, + serial: 0, + }; let deadline = Deadline::new(p.limits.wall_time_ms); // The manifest isn't read yet: every host import is linked, what it reports is dropped and // there is no storage to reach. @@ -259,19 +281,39 @@ impl Plugin { e => e, })?; p.manifest = Manifest::parse(&text)?; - host::check_granted(&p.manifest, &imports)?; - // A heavy filter's runs get the larger budget the host allows for one, which the host - // lets the user allow or refuse before installing it. - if p.manifest.budget == crate::Budget::Heavy { - p.limits.fuel_base = p.limits.fuel_base.max(p.limits.heavy_fuel); - p.limits.wall_time_ms = p.limits.wall_time_ms.max(p.limits.heavy_wall_time_ms); + if p.manifest.runtime != Runtime::Wasm { + return Err(Error::Manifest("a WebAssembly module's manifest leaves `runtime` out: \"js\" is for a JavaScript plug-in".into())); } + host::check_granted(&p.manifest, &imports)?; + p.heavy_limits(); // The other exports must exist with the right types. live.func::("vc_alloc")?; live.func::("vc_run")?; Ok(p) } + /// A heavy filter's runs get the larger budget the host allows for one, which the host lets the + /// user allow or refuse before installing it. + fn heavy_limits(&mut self) { + if self.manifest.budget == crate::Budget::Heavy { + self.limits.fuel_base = self.limits.fuel_base.max(self.limits.heavy_fuel); + self.limits.wall_time_ms = self.limits.wall_time_ms.max(self.limits.heavy_wall_time_ms); + } + } + + /// What runs its code ([`Manifest::runtime`]). + pub fn runtime(&self) -> Runtime { + self.manifest.runtime + } + + /// A JavaScript plug-in's script file name; `None` for a WebAssembly module. + pub fn script(&self) -> Option<&str> { + match &self.code { + Code::Js(script) => Some(&script.name), + Code::Wasm { .. } => None, + } + } + pub fn manifest(&self) -> &Manifest { &self.manifest } @@ -315,15 +357,16 @@ impl Plugin { /// A new instance for `run`, with the host imports of the permissions `granted` linked. When the /// module's start function fails, what it reported through the host imports goes to `report`. fn instantiate(&self, run: Run, granted: &[Permission], report: &mut Report) -> Result { + let Code::Wasm { engine, module } = &self.code else { return Err(Error::Module("not a WebAssembly binary (missing \\0asm header)".into())) }; let limits = StoreLimitsBuilder::new().memory_size(self.limits.max_memory_bytes).memories(1).tables(4).table_elements(100_000).instances(1).build(); - let mut store = Store::new(&self.engine, Host { limits, run }); + let mut store = Store::new(engine, Host { limits, run }); store.limiter(|h| &mut h.limits); // The start function (if any) runs on one slice of fuel: it runs before `call` can check // the deadline or a cancel between slices, so a heavy budget would let it run for minutes. store.set_fuel(self.limits.fuel_base.min(FUEL_SLICE)).map_err(wasm_err)?; - let linker = host::linker(&self.engine, granted); - let instance = match linker.instantiate_and_start(&mut store, &self.module) { + let linker = host::linker(engine, granted); + let instance = match linker.instantiate_and_start(&mut store, module) { Ok(instance) => instance, Err(e) => { *report = std::mem::take(&mut store.data_mut().run.report); @@ -453,6 +496,14 @@ impl Plugin { let deadline = Deadline::new(limits.wall_time_ms); let m = &self.manifest; let run = Run::new(&m.id, m.kind != Kind::Effect, true, deadline).with_storage(crate::registry::storage(&m.id)); + if let Code::Js(script) = &self.code { + // Its manifest lists no `commands`, so nothing calls it with a bridge. + if bridge.is_some() { + return Err(Error::Abi("a JavaScript plug-in makes no command calls".into())); + } + let call = crate::js::Call { input, params, limits, max_memory: self.limits.max_memory_bytes, deadline }; + return crate::js::run(script, m, &call, run, report); + } let mut live = self.instantiate(run, &m.permissions(), report)?; // Calls can be made from `vc_run` on, not from the start function. if bridge.is_some() { diff --git a/crates/ui-egui/src/dialogs/tests.rs b/crates/ui-egui/src/dialogs/tests.rs index 4561f3dc73..9196d9a1bf 100644 --- a/crates/ui-egui/src/dialogs/tests.rs +++ b/crates/ui-egui/src/dialogs/tests.rs @@ -720,6 +720,7 @@ impl PluginIntField { paint_output: false, commands: Vec::new(), command_allowlist: Vec::new(), + runtime: Default::default(), }; let mut f = PluginIntField { ctx, d: Dialog::new(plugin::KIND, json!({ "seed": start })), m, pos: egui::Pos2::ZERO }; fn number_rect(shape: &egui::Shape, text: &str) -> Option { diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index e4271f7926..a76c57fd93 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -7881,6 +7881,21 @@ variable-list-end {0}, {1} {0} i {1} @msg time budget pressupost de temps @msg memory budget (the selection is too large to hand over) pressupost de memòria (la selecció és massa gran per passar-la) @msg output size ({what} is {len} bytes, limit {max}) mida de la sortida ({what} fa {len} bytes, límit {max}) +@msg {reason} ({id}, {script} line {line}, column {column}) {reason} ({id}, {script} línia {line}, columna {column}) +@msg {reason} ({id}, {script}) {reason} ({id}, {script}) +@msg memory budget pressupost de memòria +@msg call depth profunditat de crides +@msg run(input, params) returned no output object run(input, params) no ha retornat cap objecte de sortida +@msg `runtime` "js" needs `script`: the name of the plug-in's .js file, next to the manifest `runtime` "js" necessita `script`: el nom del fitxer .js del complement, al costat del manifest +@msg `script` must be the name of a .js file in the manifest's folder: 1-128 bytes, no folder, no `:`, not starting with `.` `script` ha de ser el nom d’un fitxer .js a la carpeta del manifest: 1-128 bytes, sense carpeta, sense `:`, sense començar per `.` +@msg `source` is the script's text, given only in the JSON that plugin.install's dataBase64 takes: a .vcplugin file names its script in `script` `source` és el text de l’script i només es dona en el JSON que pren el dataBase64 de plugin.install: un fitxer .vcplugin anomena el seu script a `script` +@msg a JavaScript plug-in's manifest gives `runtime` "js" el manifest d’un complement de JavaScript indica `runtime` "js" +@msg `runtime` "js" is for an object filter (`kind` "filter"), not `kind` "{kind}" `runtime` "js" és per a un filtre d’objectes (`kind` "filter"), no per a `kind` "{kind}" +@msg a JavaScript plug-in can't list the permission `{name}`: of the host's permissions it may list `progress` un complement de JavaScript no pot incloure el permís `{name}`: dels permisos de l’amfitrió pot incloure `progress` +@msg a WebAssembly module's manifest leaves `runtime` out: "js" is for a JavaScript plug-in el manifest d’un mòdul WebAssembly omet `runtime`: "js" és per a un complement de JavaScript +@msg a JavaScript plug-in makes no command calls un complement de JavaScript no crida ordres +@msg vc.progress(done, total) takes two numbers vc.progress(done, total) pren dos nombres +@msg vc.log(level, text) takes a level, 0 (error), 1 (warning), 2 (information) or 3 (debug), and a string vc.log(level, text) pren un nivell, 0 (error), 1 (avís), 2 (informació) o 3 (depuració), i una cadena @msg the plug-in's grant can't be removed from the plug-in store el permís del complement no es pot treure del magatzem de complements @msg permission `{shown}` is reserved for a later plug-in API; this host doesn't grant it el permís `{shown}` està reservat per a una API de complements posterior; aquest amfitrió no el concedeix @msg unknown permission `{shown}` permís desconegut `{shown}` diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index 488df173c3..ec70b8d8bc 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -7491,6 +7491,21 @@ axis Y Axis osa Y @msg time budget časový rozpočet @msg memory budget (the selection is too large to hand over) rozpočet paměti (výběr je příliš velký na předání) @msg output size ({what} is {len} bytes, limit {max}) velikost výstupu ({what} má {len} bajtů, limit {max}) +@msg {reason} ({id}, {script} line {line}, column {column}) {reason} ({id}, {script} řádek {line}, sloupec {column}) +@msg {reason} ({id}, {script}) {reason} ({id}, {script}) +@msg memory budget rozpočet paměti +@msg call depth hloubka volání +@msg run(input, params) returned no output object run(input, params) nevrátila žádný výstupní objekt +@msg `runtime` "js" needs `script`: the name of the plug-in's .js file, next to the manifest `runtime` "js" vyžaduje `script`: název souboru .js zásuvného modulu vedle manifestu +@msg `script` must be the name of a .js file in the manifest's folder: 1-128 bytes, no folder, no `:`, not starting with `.` `script` musí být název souboru .js ve složce manifestu: 1-128 bajtů, bez složky, bez `:`, nesmí začínat `.` +@msg `source` is the script's text, given only in the JSON that plugin.install's dataBase64 takes: a .vcplugin file names its script in `script` `source` je text skriptu a uvádí se jen v JSON, které přijímá dataBase64 příkazu plugin.install: soubor .vcplugin uvádí svůj skript v `script` +@msg a JavaScript plug-in's manifest gives `runtime` "js" manifest zásuvného modulu v JavaScriptu uvádí `runtime` "js" +@msg `runtime` "js" is for an object filter (`kind` "filter"), not `kind` "{kind}" `runtime` "js" je pro filtr objektů (`kind` "filter"), ne pro `kind` "{kind}" +@msg a JavaScript plug-in can't list the permission `{name}`: of the host's permissions it may list `progress` zásuvný modul v JavaScriptu nemůže uvést oprávnění `{name}`: z oprávnění hostitele smí uvést `progress` +@msg a WebAssembly module's manifest leaves `runtime` out: "js" is for a JavaScript plug-in manifest modulu WebAssembly vynechává `runtime`: "js" je pro zásuvný modul v JavaScriptu +@msg a JavaScript plug-in makes no command calls zásuvný modul v JavaScriptu nevolá žádné příkazy +@msg vc.progress(done, total) takes two numbers vc.progress(done, total) přijímá dvě čísla +@msg vc.log(level, text) takes a level, 0 (error), 1 (warning), 2 (information) or 3 (debug), and a string vc.log(level, text) přijímá úroveň, 0 (chyba), 1 (varování), 2 (informace) nebo 3 (ladění), a řetězec @msg the plug-in's grant can't be removed from the plug-in store oprávnění zásuvného modulu nelze odebrat z úložiště zásuvných modulů @msg permission `{shown}` is reserved for a later plug-in API; this host doesn't grant it oprávnění `{shown}` je vyhrazeno pro pozdější API zásuvných modulů; tento hostitel ho neuděluje @msg unknown permission `{shown}` neznámé oprávnění `{shown}` diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index 302ab6aa69..fdd823b554 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -703,6 +703,21 @@ liquify-list-end {0}, {1} {0} og {1} @msg time budget tidsbudget @msg memory budget (the selection is too large to hand over) hukommelsesbudget (markeringen er for stor til at blive overdraget) @msg output size ({what} is {len} bytes, limit {max}) outputstørrelse ({what} fylder {len} byte, grænse {max}) +@msg {reason} ({id}, {script} line {line}, column {column}) {reason} ({id}, {script} linje {line}, kolonne {column}) +@msg {reason} ({id}, {script}) {reason} ({id}, {script}) +@msg memory budget hukommelsesbudget +@msg call depth kaldedybde +@msg run(input, params) returned no output object run(input, params) returnerede intet outputobjekt +@msg `runtime` "js" needs `script`: the name of the plug-in's .js file, next to the manifest `runtime` "js" kræver `script`: navnet på plug-in'ets .js-fil ved siden af manifestet +@msg `script` must be the name of a .js file in the manifest's folder: 1-128 bytes, no folder, no `:`, not starting with `.` `script` skal være navnet på en .js-fil i manifestets mappe: 1-128 byte, ingen mappe, intet `:`, må ikke starte med `.` +@msg `source` is the script's text, given only in the JSON that plugin.install's dataBase64 takes: a .vcplugin file names its script in `script` `source` er scriptets tekst og angives kun i den JSON, som dataBase64 i plugin.install tager: en .vcplugin-fil navngiver sit script i `script` +@msg a JavaScript plug-in's manifest gives `runtime` "js" et JavaScript-plug-ins manifest angiver `runtime` "js" +@msg `runtime` "js" is for an object filter (`kind` "filter"), not `kind` "{kind}" `runtime` "js" er til et objektfilter (`kind` "filter"), ikke `kind` "{kind}" +@msg a JavaScript plug-in can't list the permission `{name}`: of the host's permissions it may list `progress` et JavaScript-plug-in kan ikke angive tilladelsen `{name}`: af værtens tilladelser må det angive `progress` +@msg a WebAssembly module's manifest leaves `runtime` out: "js" is for a JavaScript plug-in et WebAssembly-moduls manifest udelader `runtime`: "js" er til et JavaScript-plug-in +@msg a JavaScript plug-in makes no command calls et JavaScript-plug-in kalder ingen kommandoer +@msg vc.progress(done, total) takes two numbers vc.progress(done, total) tager to tal +@msg vc.log(level, text) takes a level, 0 (error), 1 (warning), 2 (information) or 3 (debug), and a string vc.log(level, text) tager et niveau, 0 (fejl), 1 (advarsel), 2 (information) eller 3 (fejlsøgning), og en streng @msg the plug-in's grant can't be removed from the plug-in store plug-in'ets tilladelse kan ikke fjernes fra plug-in-lageret @msg permission `{shown}` is reserved for a later plug-in API; this host doesn't grant it tilladelsen `{shown}` er reserveret til et senere plug-in-API; denne vært tildeler den ikke @msg unknown permission `{shown}` ukendt tilladelse `{shown}` diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index 9482345f18..54340d7189 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -7074,6 +7074,21 @@ axis Y Axis Y-Achse @msg time budget Zeitbudget @msg memory budget (the selection is too large to hand over) Speicherbudget (die Auswahl ist zu groß zum Übergeben) @msg output size ({what} is {len} bytes, limit {max}) Ausgabegröße ({what} ist {len} Byte groß, Grenze {max}) +@msg {reason} ({id}, {script} line {line}, column {column}) {reason} ({id}, {script} Zeile {line}, Spalte {column}) +@msg {reason} ({id}, {script}) {reason} ({id}, {script}) +@msg memory budget Speicherbudget +@msg call depth Aufruftiefe +@msg run(input, params) returned no output object run(input, params) hat kein Ausgabeobjekt zurückgegeben +@msg `runtime` "js" needs `script`: the name of the plug-in's .js file, next to the manifest `runtime` "js" braucht `script`: den Namen der .js-Datei des Plug-ins neben dem Manifest +@msg `script` must be the name of a .js file in the manifest's folder: 1-128 bytes, no folder, no `:`, not starting with `.` `script` muss der Name einer .js-Datei im Ordner des Manifests sein: 1-128 Byte, kein Ordner, kein `:`, nicht mit `.` beginnend +@msg `source` is the script's text, given only in the JSON that plugin.install's dataBase64 takes: a .vcplugin file names its script in `script` `source` ist der Text des Skripts und steht nur in dem JSON, das dataBase64 von plugin.install übernimmt: eine .vcplugin-Datei nennt ihr Skript in `script` +@msg a JavaScript plug-in's manifest gives `runtime` "js" das Manifest eines JavaScript-Plug-ins gibt `runtime` "js" an +@msg `runtime` "js" is for an object filter (`kind` "filter"), not `kind` "{kind}" `runtime` "js" gilt für einen Objektfilter (`kind` "filter"), nicht für `kind` "{kind}" +@msg a JavaScript plug-in can't list the permission `{name}`: of the host's permissions it may list `progress` ein JavaScript-Plug-in kann die Berechtigung `{name}` nicht aufführen: von den Berechtigungen des Hosts darf es `progress` aufführen +@msg a WebAssembly module's manifest leaves `runtime` out: "js" is for a JavaScript plug-in das Manifest eines WebAssembly-Moduls lässt `runtime` weg: "js" gilt für ein JavaScript-Plug-in +@msg a JavaScript plug-in makes no command calls ein JavaScript-Plug-in ruft keine Befehle auf +@msg vc.progress(done, total) takes two numbers vc.progress(done, total) nimmt zwei Zahlen +@msg vc.log(level, text) takes a level, 0 (error), 1 (warning), 2 (information) or 3 (debug), and a string vc.log(level, text) nimmt eine Stufe, 0 (Fehler), 1 (Warnung), 2 (Information) oder 3 (Debug), und eine Zeichenfolge @msg the plug-in's grant can't be removed from the plug-in store die Berechtigung des Plug-ins kann nicht aus dem Plug-in-Speicher entfernt werden @msg permission `{shown}` is reserved for a later plug-in API; this host doesn't grant it die Berechtigung `{shown}` ist für eine spätere Plug-in-API reserviert; dieser Host gewährt sie nicht @msg unknown permission `{shown}` unbekannte Berechtigung `{shown}` diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index 434d0cc0b8..76a5509796 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -7481,6 +7481,21 @@ axis Y Axis Άξονας Y @msg time budget χρονικός προϋπολογισμός @msg memory budget (the selection is too large to hand over) προϋπολογισμός μνήμης (η επιλογή είναι πολύ μεγάλη για να παραδοθεί) @msg output size ({what} is {len} bytes, limit {max}) μέγεθος εξόδου ({what}: {len} byte, όριο {max}) +@msg {reason} ({id}, {script} line {line}, column {column}) {reason} ({id}, {script} γραμμή {line}, στήλη {column}) +@msg {reason} ({id}, {script}) {reason} ({id}, {script}) +@msg memory budget προϋπολογισμός μνήμης +@msg call depth βάθος κλήσεων +@msg run(input, params) returned no output object η run(input, params) δεν επέστρεψε αντικείμενο εξόδου +@msg `runtime` "js" needs `script`: the name of the plug-in's .js file, next to the manifest το `runtime` "js" χρειάζεται `script`: το όνομα του αρχείου .js του προσθέτου, δίπλα στο αρχείο δηλώσεων +@msg `script` must be the name of a .js file in the manifest's folder: 1-128 bytes, no folder, no `:`, not starting with `.` το `script` πρέπει να είναι το όνομα ενός αρχείου .js στον φάκελο του αρχείου δηλώσεων: 1-128 byte, χωρίς φάκελο, χωρίς `:`, χωρίς να αρχίζει με `.` +@msg `source` is the script's text, given only in the JSON that plugin.install's dataBase64 takes: a .vcplugin file names its script in `script` το `source` είναι το κείμενο του σεναρίου και δίνεται μόνο στο JSON που δέχεται το dataBase64 της plugin.install: ένα αρχείο .vcplugin ονομάζει το σενάριό του στο `script` +@msg a JavaScript plug-in's manifest gives `runtime` "js" το αρχείο δηλώσεων ενός προσθέτου JavaScript δίνει `runtime` "js" +@msg `runtime` "js" is for an object filter (`kind` "filter"), not `kind` "{kind}" το `runtime` "js" είναι για φίλτρο αντικειμένων (`kind` "filter"), όχι για `kind` "{kind}" +@msg a JavaScript plug-in can't list the permission `{name}`: of the host's permissions it may list `progress` ένα πρόσθετο JavaScript δεν μπορεί να δηλώσει την άδεια `{name}`: από τις άδειες του κεντρικού υπολογιστή μπορεί να δηλώσει την `progress` +@msg a WebAssembly module's manifest leaves `runtime` out: "js" is for a JavaScript plug-in το αρχείο δηλώσεων μιας μονάδας WebAssembly παραλείπει το `runtime`: το "js" είναι για πρόσθετο JavaScript +@msg a JavaScript plug-in makes no command calls ένα πρόσθετο JavaScript δεν καλεί εντολές +@msg vc.progress(done, total) takes two numbers η vc.progress(done, total) δέχεται δύο αριθμούς +@msg vc.log(level, text) takes a level, 0 (error), 1 (warning), 2 (information) or 3 (debug), and a string η vc.log(level, text) δέχεται ένα επίπεδο, 0 (σφάλμα), 1 (προειδοποίηση), 2 (πληροφορία) ή 3 (εντοπισμός σφαλμάτων), και μια συμβολοσειρά @msg the plug-in's grant can't be removed from the plug-in store η άδεια του πρόσθετου δεν μπορεί να αφαιρεθεί από τον χώρο αποθήκευσης πρόσθετων @msg permission `{shown}` is reserved for a later plug-in API; this host doesn't grant it το δικαίωμα `{shown}` είναι δεσμευμένο για μεταγενέστερο API προσθέτων· αυτός ο κεντρικός υπολογιστής δεν το παραχωρεί @msg unknown permission `{shown}` άγνωστο δικαίωμα `{shown}` diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index 3f83e928e4..00af36024c 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -7467,6 +7467,21 @@ axis Y Axis Eje Y @msg time budget presupuesto de tiempo @msg memory budget (the selection is too large to hand over) presupuesto de memoria (la selección es demasiado grande para entregarla) @msg output size ({what} is {len} bytes, limit {max}) tamaño de salida ({what} ocupa {len} bytes, límite {max}) +@msg {reason} ({id}, {script} line {line}, column {column}) {reason} ({id}, {script} línea {line}, columna {column}) +@msg {reason} ({id}, {script}) {reason} ({id}, {script}) +@msg memory budget presupuesto de memoria +@msg call depth profundidad de llamadas +@msg run(input, params) returned no output object run(input, params) no devolvió ningún objeto de salida +@msg `runtime` "js" needs `script`: the name of the plug-in's .js file, next to the manifest `runtime` "js" necesita `script`: el nombre del archivo .js del plugin, junto al manifiesto +@msg `script` must be the name of a .js file in the manifest's folder: 1-128 bytes, no folder, no `:`, not starting with `.` `script` debe ser el nombre de un archivo .js en la carpeta del manifiesto: 1-128 bytes, sin carpeta, sin `:`, sin empezar por `.` +@msg `source` is the script's text, given only in the JSON that plugin.install's dataBase64 takes: a .vcplugin file names its script in `script` `source` es el texto del script y solo se da en el JSON que toma el dataBase64 de plugin.install: un archivo .vcplugin nombra su script en `script` +@msg a JavaScript plug-in's manifest gives `runtime` "js" el manifiesto de un plugin de JavaScript indica `runtime` "js" +@msg `runtime` "js" is for an object filter (`kind` "filter"), not `kind` "{kind}" `runtime` "js" es para un filtro de objetos (`kind` "filter"), no para `kind` "{kind}" +@msg a JavaScript plug-in can't list the permission `{name}`: of the host's permissions it may list `progress` un plugin de JavaScript no puede incluir el permiso `{name}`: de los permisos del host puede incluir `progress` +@msg a WebAssembly module's manifest leaves `runtime` out: "js" is for a JavaScript plug-in el manifiesto de un módulo WebAssembly omite `runtime`: "js" es para un plugin de JavaScript +@msg a JavaScript plug-in makes no command calls un plugin de JavaScript no llama a comandos +@msg vc.progress(done, total) takes two numbers vc.progress(done, total) recibe dos números +@msg vc.log(level, text) takes a level, 0 (error), 1 (warning), 2 (information) or 3 (debug), and a string vc.log(level, text) recibe un nivel, 0 (error), 1 (advertencia), 2 (información) o 3 (depuración), y una cadena @msg the plug-in's grant can't be removed from the plug-in store el permiso del plugin no se puede quitar del almacén de plugins @msg permission `{shown}` is reserved for a later plug-in API; this host doesn't grant it el permiso `{shown}` está reservado para una API de plugins posterior; este host no lo concede @msg unknown permission `{shown}` permiso desconocido `{shown}` diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index a4d85b23e8..11d9673102 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -7558,6 +7558,21 @@ axis Y Axis Y-akseli @msg time budget aikabudjetti @msg memory budget (the selection is too large to hand over) muistibudjetti (valinta on liian suuri luovutettavaksi) @msg output size ({what} is {len} bytes, limit {max}) tulosteen koko ({what}: {len} tavua, raja {max}) +@msg {reason} ({id}, {script} line {line}, column {column}) {reason} ({id}, {script} rivi {line}, sarake {column}) +@msg {reason} ({id}, {script}) {reason} ({id}, {script}) +@msg memory budget muistibudjetti +@msg call depth kutsusyvyys +@msg run(input, params) returned no output object run(input, params) ei palauttanut tulosobjektia +@msg `runtime` "js" needs `script`: the name of the plug-in's .js file, next to the manifest `runtime` "js" tarvitsee avaimen `script`: laajennuksen .js-tiedoston nimen manifestin vieressä +@msg `script` must be the name of a .js file in the manifest's folder: 1-128 bytes, no folder, no `:`, not starting with `.` `script` on oltava manifestin kansiossa olevan .js-tiedoston nimi: 1-128 tavua, ei kansiota, ei merkkiä `:`, ei alussa merkkiä `.` +@msg `source` is the script's text, given only in the JSON that plugin.install's dataBase64 takes: a .vcplugin file names its script in `script` `source` on komentosarjan teksti, ja se annetaan vain JSONissa, jonka plugin.install-komennon dataBase64 ottaa: .vcplugin-tiedosto nimeää komentosarjansa avaimessa `script` +@msg a JavaScript plug-in's manifest gives `runtime` "js" JavaScript-laajennuksen manifesti antaa `runtime` "js" +@msg `runtime` "js" is for an object filter (`kind` "filter"), not `kind` "{kind}" `runtime` "js" on objektisuodattimelle (`kind` "filter"), ei arvolle `kind` "{kind}" +@msg a JavaScript plug-in can't list the permission `{name}`: of the host's permissions it may list `progress` JavaScript-laajennus ei voi luetella lupaa `{name}`: isännän luvista se voi luetella luvan `progress` +@msg a WebAssembly module's manifest leaves `runtime` out: "js" is for a JavaScript plug-in WebAssembly-moduulin manifesti jättää avaimen `runtime` pois: "js" on JavaScript-laajennukselle +@msg a JavaScript plug-in makes no command calls JavaScript-laajennus ei kutsu komentoja +@msg vc.progress(done, total) takes two numbers vc.progress(done, total) ottaa kaksi lukua +@msg vc.log(level, text) takes a level, 0 (error), 1 (warning), 2 (information) or 3 (debug), and a string vc.log(level, text) ottaa tason, 0 (virhe), 1 (varoitus), 2 (tieto) tai 3 (virheenjäljitys), ja merkkijonon @msg the plug-in's grant can't be removed from the plug-in store laajennuksen käyttöoikeutta ei voi poistaa laajennusvarastosta @msg permission `{shown}` is reserved for a later plug-in API; this host doesn't grant it käyttöoikeus `{shown}` on varattu myöhemmälle laajennus-API:lle; tämä isäntä ei myönnä sitä @msg unknown permission `{shown}` tuntematon käyttöoikeus `{shown}` diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 8f56486157..ebf84b7829 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -7488,6 +7488,21 @@ axis Y Axis Axe Y @msg time budget budget de temps @msg memory budget (the selection is too large to hand over) budget mémoire (la sélection est trop grande pour être transmise) @msg output size ({what} is {len} bytes, limit {max}) taille de sortie ({what} fait {len} octets, limite {max}) +@msg {reason} ({id}, {script} line {line}, column {column}) {reason} ({id}, {script} ligne {line}, colonne {column}) +@msg {reason} ({id}, {script}) {reason} ({id}, {script}) +@msg memory budget budget mémoire +@msg call depth profondeur d’appel +@msg run(input, params) returned no output object run(input, params) n’a renvoyé aucun objet de sortie +@msg `runtime` "js" needs `script`: the name of the plug-in's .js file, next to the manifest `runtime` "js" a besoin de `script`, le nom du fichier .js du plug-in placé à côté du manifeste +@msg `script` must be the name of a .js file in the manifest's folder: 1-128 bytes, no folder, no `:`, not starting with `.` `script` doit être le nom d’un fichier .js dans le dossier du manifeste (1-128 octets, sans dossier, sans `:`, ne commençant pas par `.`) +@msg `source` is the script's text, given only in the JSON that plugin.install's dataBase64 takes: a .vcplugin file names its script in `script` `source` est le texte du script, donné uniquement dans le JSON que prend le dataBase64 de plugin.install, et un fichier .vcplugin nomme son script dans `script` +@msg a JavaScript plug-in's manifest gives `runtime` "js" le manifeste d’un plug-in JavaScript indique `runtime` "js" +@msg `runtime` "js" is for an object filter (`kind` "filter"), not `kind` "{kind}" `runtime` "js" est réservé à un filtre d’objets (`kind` "filter"), pas à `kind` "{kind}" +@msg a JavaScript plug-in can't list the permission `{name}`: of the host's permissions it may list `progress` un plug-in JavaScript ne peut pas lister l’autorisation `{name}`, et parmi les autorisations de l’hôte, il peut lister `progress` +@msg a WebAssembly module's manifest leaves `runtime` out: "js" is for a JavaScript plug-in le manifeste d’un module WebAssembly omet `runtime`, car "js" est réservé à un plug-in JavaScript +@msg a JavaScript plug-in makes no command calls un plug-in JavaScript n’appelle aucune commande +@msg vc.progress(done, total) takes two numbers vc.progress(done, total) prend deux nombres +@msg vc.log(level, text) takes a level, 0 (error), 1 (warning), 2 (information) or 3 (debug), and a string vc.log(level, text) prend un niveau, 0 (erreur), 1 (avertissement), 2 (information) ou 3 (débogage), et une chaîne @msg the plug-in's grant can't be removed from the plug-in store l’autorisation du plug-in ne peut pas être retirée du magasin de plug-ins @msg unknown permission `{shown}` autorisation inconnue `{shown}` @msg “{name}” asks for the permissions {asked}: a person has to approve them in the desktop app, or pass `grant` in a session started with --allow-plugin-grants « {name} » demande les autorisations {asked} : une personne doit les approuver dans l’application de bureau, ou passez `grant` dans une session démarrée avec --allow-plugin-grants diff --git a/crates/ui-egui/src/i18n/hi.tsv b/crates/ui-egui/src/i18n/hi.tsv index e9509d9202..dc14ecc572 100644 --- a/crates/ui-egui/src/i18n/hi.tsv +++ b/crates/ui-egui/src/i18n/hi.tsv @@ -8736,6 +8736,21 @@ liquify-list-end {0}, {1} {0} और {1} @msg outlineText {v}: true or false outlineText {v}: true या false @msg output intent profile: {e} उत्पादन आशय प्रोफ़ाइल: {e} @msg output size ({what} is {len} bytes, limit {max}) आउटपुट का आकार ({what} {len} बाइट्स का है, सीमा {max}) +@msg {reason} ({id}, {script} line {line}, column {column}) {reason} ({id}, {script} पंक्ति {line}, स्तंभ {column}) +@msg {reason} ({id}, {script}) {reason} ({id}, {script}) +@msg memory budget स्मृति बजट +@msg call depth कॉल गहराई +@msg run(input, params) returned no output object run(input, params) ने कोई आउटपुट ऑब्जेक्ट नहीं लौटाया +@msg `runtime` "js" needs `script`: the name of the plug-in's .js file, next to the manifest `runtime` "js" को `script` चाहिए: मैनिफ़ेस्ट के पास प्लग-इन की .js फ़ाइल का नाम +@msg `script` must be the name of a .js file in the manifest's folder: 1-128 bytes, no folder, no `:`, not starting with `.` `script` मैनिफ़ेस्ट के फ़ोल्डर में किसी .js फ़ाइल का नाम होना चाहिए: 1-128 बाइट्स, कोई फ़ोल्डर नहीं, कोई `:` नहीं, `.` से शुरू नहीं +@msg `source` is the script's text, given only in the JSON that plugin.install's dataBase64 takes: a .vcplugin file names its script in `script` `source` स्क्रिप्ट का टेक्स्ट है, जो केवल उस JSON में दिया जाता है जिसे plugin.install का dataBase64 लेता है: .vcplugin फ़ाइल अपनी स्क्रिप्ट का नाम `script` में देती है +@msg a JavaScript plug-in's manifest gives `runtime` "js" JavaScript प्लग-इन का मैनिफ़ेस्ट `runtime` "js" देता है +@msg `runtime` "js" is for an object filter (`kind` "filter"), not `kind` "{kind}" `runtime` "js" ऑब्जेक्ट फ़िल्टर (`kind` "filter") के लिए है, `kind` "{kind}" के लिए नहीं +@msg a JavaScript plug-in can't list the permission `{name}`: of the host's permissions it may list `progress` JavaScript प्लग-इन अनुमति `{name}` सूचीबद्ध नहीं कर सकता: होस्ट की अनुमतियों में से वह `progress` सूचीबद्ध कर सकता है +@msg a WebAssembly module's manifest leaves `runtime` out: "js" is for a JavaScript plug-in WebAssembly मॉड्यूल का मैनिफ़ेस्ट `runtime` छोड़ देता है: "js" JavaScript प्लग-इन के लिए है +@msg a JavaScript plug-in makes no command calls JavaScript प्लग-इन कोई कमांड कॉल नहीं करता +@msg vc.progress(done, total) takes two numbers vc.progress(done, total) दो संख्याएँ लेता है +@msg vc.log(level, text) takes a level, 0 (error), 1 (warning), 2 (information) or 3 (debug), and a string vc.log(level, text) एक स्तर, 0 (त्रुटि), 1 (चेतावनी), 2 (जानकारी) या 3 (डीबग), और एक स्ट्रिंग लेता है @msg output.destination: {_1} files are CMYK, and “{name}” is an RGB profile output.destination: {_1} फ़ाइलें CMYK हैं, और "{name}" एक RGB प्रोफ़ाइल है @msg output.destination: {e} output.destination: {e} @msg output.destination: no RGB or CMYK profile is called “{name}” output.destination: "{name}" नाम की कोई RGB या CMYK प्रोफ़ाइल नहीं है diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index 87f050ef0d..ac2857ecf7 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -7476,6 +7476,21 @@ axis Y Axis Y tengely @msg time budget időkeret @msg memory budget (the selection is too large to hand over) memóriakeret (a kijelölés túl nagy az átadáshoz) @msg output size ({what} is {len} bytes, limit {max}) kimenet mérete ({what}: {len} bájt, korlát {max}) +@msg {reason} ({id}, {script} line {line}, column {column}) {reason} ({id}, {script}, {line}. sor, {column}. oszlop) +@msg {reason} ({id}, {script}) {reason} ({id}, {script}) +@msg memory budget memóriakeret +@msg call depth hívási mélység +@msg run(input, params) returned no output object a run(input, params) nem adott vissza kimeneti objektumot +@msg `runtime` "js" needs `script`: the name of the plug-in's .js file, next to the manifest a `runtime` "js" értékhez `script` kell: a bővítmény .js fájljának neve a leíró mellett +@msg `script` must be the name of a .js file in the manifest's folder: 1-128 bytes, no folder, no `:`, not starting with `.` a `script` a leíró mappájában lévő .js fájl neve legyen: 1-128 bájt, mappa nélkül, `:` nélkül, és nem kezdődhet `.` karakterrel +@msg `source` is the script's text, given only in the JSON that plugin.install's dataBase64 takes: a .vcplugin file names its script in `script` a `source` a parancsfájl szövege, és csak abban a JSON-ban adható meg, amelyet a plugin.install dataBase64 paramétere fogad: a .vcplugin fájl a `script` kulcsban nevezi meg a parancsfájlját +@msg a JavaScript plug-in's manifest gives `runtime` "js" egy JavaScript-bővítmény leírója `runtime` "js" értéket ad meg +@msg `runtime` "js" is for an object filter (`kind` "filter"), not `kind` "{kind}" a `runtime` "js" objektumszűrőhöz való (`kind` "filter"), nem `kind` "{kind}" értékhez +@msg a JavaScript plug-in can't list the permission `{name}`: of the host's permissions it may list `progress` egy JavaScript-bővítmény nem sorolhatja fel a(z) `{name}` engedélyt: a gazdagép engedélyei közül a `progress` engedélyt sorolhatja fel +@msg a WebAssembly module's manifest leaves `runtime` out: "js" is for a JavaScript plug-in egy WebAssembly-modul leírója elhagyja a `runtime` kulcsot: a "js" JavaScript-bővítményhez való +@msg a JavaScript plug-in makes no command calls egy JavaScript-bővítmény nem hív parancsokat +@msg vc.progress(done, total) takes two numbers a vc.progress(done, total) két számot vár +@msg vc.log(level, text) takes a level, 0 (error), 1 (warning), 2 (information) or 3 (debug), and a string a vc.log(level, text) egy szintet, 0 (hiba), 1 (figyelmeztetés), 2 (információ) vagy 3 (hibakeresés), és egy karakterláncot vár @msg the plug-in's grant can't be removed from the plug-in store a bővítmény engedélye nem távolítható el a bővítménytárból @msg permission `{shown}` is reserved for a later plug-in API; this host doesn't grant it a(z) `{shown}` engedély egy későbbi bővítmény-API számára van fenntartva; ez a gazdaprogram nem adja meg @msg unknown permission `{shown}` ismeretlen engedély: `{shown}` diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index 924d3d80b5..ad06390db5 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -585,6 +585,21 @@ @msg time budget anggaran waktu @msg memory budget (the selection is too large to hand over) anggaran memori (seleksi terlalu besar untuk diserahkan) @msg output size ({what} is {len} bytes, limit {max}) ukuran keluaran ({what} berukuran {len} byte, batas {max}) +@msg {reason} ({id}, {script} line {line}, column {column}) {reason} ({id}, {script} baris {line}, kolom {column}) +@msg {reason} ({id}, {script}) {reason} ({id}, {script}) +@msg memory budget anggaran memori +@msg call depth kedalaman panggilan +@msg run(input, params) returned no output object run(input, params) tidak mengembalikan objek keluaran +@msg `runtime` "js" needs `script`: the name of the plug-in's .js file, next to the manifest `runtime` "js" memerlukan `script`: nama file .js plug-in, di samping manifes +@msg `script` must be the name of a .js file in the manifest's folder: 1-128 bytes, no folder, no `:`, not starting with `.` `script` harus berupa nama file .js di folder manifes: 1-128 byte, tanpa folder, tanpa `:`, tidak diawali `.` +@msg `source` is the script's text, given only in the JSON that plugin.install's dataBase64 takes: a .vcplugin file names its script in `script` `source` adalah teks skrip dan hanya diberikan dalam JSON yang diterima dataBase64 plugin.install: file .vcplugin menamai skripnya di `script` +@msg a JavaScript plug-in's manifest gives `runtime` "js" manifes plug-in JavaScript memberikan `runtime` "js" +@msg `runtime` "js" is for an object filter (`kind` "filter"), not `kind` "{kind}" `runtime` "js" untuk filter objek (`kind` "filter"), bukan `kind` "{kind}" +@msg a JavaScript plug-in can't list the permission `{name}`: of the host's permissions it may list `progress` plug-in JavaScript tidak dapat mencantumkan izin `{name}`: dari izin host, plug-in ini boleh mencantumkan `progress` +@msg a WebAssembly module's manifest leaves `runtime` out: "js" is for a JavaScript plug-in manifes modul WebAssembly menghilangkan `runtime`: "js" untuk plug-in JavaScript +@msg a JavaScript plug-in makes no command calls plug-in JavaScript tidak memanggil perintah +@msg vc.progress(done, total) takes two numbers vc.progress(done, total) menerima dua angka +@msg vc.log(level, text) takes a level, 0 (error), 1 (warning), 2 (information) or 3 (debug), and a string vc.log(level, text) menerima level, 0 (kesalahan), 1 (peringatan), 2 (informasi), atau 3 (debug), dan string @msg the plug-in's grant can't be removed from the plug-in store izin yang diberikan kepada plug-in tidak dapat dihapus dari penyimpanan plug-in @msg permission `{shown}` is reserved for a later plug-in API; this host doesn't grant it izin `{shown}` dicadangkan untuk API plug-in yang lebih baru; host ini tidak memberikannya @msg unknown permission `{shown}` izin tidak dikenal `{shown}` diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index 5f47e3f117..98435ba132 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -7113,6 +7113,21 @@ axis Y Axis Asse Y @msg time budget budget di tempo @msg memory budget (the selection is too large to hand over) budget di memoria (la selezione è troppo grande per essere passata) @msg output size ({what} is {len} bytes, limit {max}) dimensione dell’output ({what} è di {len} byte, limite {max}) +@msg {reason} ({id}, {script} line {line}, column {column}) {reason} ({id}, {script} riga {line}, colonna {column}) +@msg {reason} ({id}, {script}) {reason} ({id}, {script}) +@msg memory budget budget di memoria +@msg call depth profondità delle chiamate +@msg run(input, params) returned no output object run(input, params) non ha restituito alcun oggetto di output +@msg `runtime` "js" needs `script`: the name of the plug-in's .js file, next to the manifest `runtime` "js" richiede `script`: il nome del file .js del plug-in, accanto al manifest +@msg `script` must be the name of a .js file in the manifest's folder: 1-128 bytes, no folder, no `:`, not starting with `.` `script` deve essere il nome di un file .js nella cartella del manifest: 1-128 byte, nessuna cartella, nessun `:`, senza iniziare con `.` +@msg `source` is the script's text, given only in the JSON that plugin.install's dataBase64 takes: a .vcplugin file names its script in `script` `source` è il testo dello script, indicato solo nel JSON che riceve il dataBase64 di plugin.install: un file .vcplugin indica il proprio script in `script` +@msg a JavaScript plug-in's manifest gives `runtime` "js" il manifest di un plug-in JavaScript indica `runtime` "js" +@msg `runtime` "js" is for an object filter (`kind` "filter"), not `kind` "{kind}" `runtime` "js" è per un filtro di oggetti (`kind` "filter"), non per `kind` "{kind}" +@msg a JavaScript plug-in can't list the permission `{name}`: of the host's permissions it may list `progress` un plug-in JavaScript non può elencare il permesso `{name}`: dei permessi dell’host può elencare `progress` +@msg a WebAssembly module's manifest leaves `runtime` out: "js" is for a JavaScript plug-in il manifest di un modulo WebAssembly omette `runtime`: "js" è per un plug-in JavaScript +@msg a JavaScript plug-in makes no command calls un plug-in JavaScript non chiama comandi +@msg vc.progress(done, total) takes two numbers vc.progress(done, total) accetta due numeri +@msg vc.log(level, text) takes a level, 0 (error), 1 (warning), 2 (information) or 3 (debug), and a string vc.log(level, text) accetta un livello, 0 (errore), 1 (avviso), 2 (informazione) o 3 (debug), e una stringa @msg the plug-in's grant can't be removed from the plug-in store il permesso del plug-in non può essere rimosso dall’archivio dei plug-in @msg permission `{shown}` is reserved for a later plug-in API; this host doesn't grant it l’autorizzazione `{shown}` è riservata a un’API dei plug-in successiva; questo host non la concede @msg unknown permission `{shown}` autorizzazione sconosciuta `{shown}` diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index 9a1b5f6354..5541c569fa 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -7188,6 +7188,21 @@ axis Y Axis Y 軸 @msg time budget 時間予算 @msg memory budget (the selection is too large to hand over) メモリ予算 (選択範囲が大きすぎて渡せません) @msg output size ({what} is {len} bytes, limit {max}) 出力サイズ ({what} は {len} バイト、上限 {max}) +@msg {reason} ({id}, {script} line {line}, column {column}) {reason} ({id}、{script} {line} 行 {column} 列) +@msg {reason} ({id}, {script}) {reason} ({id}、{script}) +@msg memory budget メモリ予算 +@msg call depth 呼び出しの深さ +@msg run(input, params) returned no output object run(input, params) が出力オブジェクトを返しませんでした +@msg `runtime` "js" needs `script`: the name of the plug-in's .js file, next to the manifest `runtime` "js" には `script` が必要です: マニフェストと同じ場所にあるプラグインの .js ファイルの名前 +@msg `script` must be the name of a .js file in the manifest's folder: 1-128 bytes, no folder, no `:`, not starting with `.` `script` はマニフェストのフォルダーにある .js ファイルの名前にしてください: 1-128 バイト、フォルダーなし、`:` なし、`.` で始まらないこと +@msg `source` is the script's text, given only in the JSON that plugin.install's dataBase64 takes: a .vcplugin file names its script in `script` `source` はスクリプトのテキストで、plugin.install の dataBase64 が受け取る JSON でだけ指定します: .vcplugin ファイルはスクリプトを `script` で指定します +@msg a JavaScript plug-in's manifest gives `runtime` "js" JavaScript プラグインのマニフェストは `runtime` "js" を指定します +@msg `runtime` "js" is for an object filter (`kind` "filter"), not `kind` "{kind}" `runtime` "js" はオブジェクトフィルター (`kind` "filter") 用で、`kind` "{kind}" 用ではありません +@msg a JavaScript plug-in can't list the permission `{name}`: of the host's permissions it may list `progress` JavaScript プラグインは権限 `{name}` を指定できません: ホストの権限のうち指定できるのは `progress` です +@msg a WebAssembly module's manifest leaves `runtime` out: "js" is for a JavaScript plug-in WebAssembly モジュールのマニフェストでは `runtime` を省略します: "js" は JavaScript プラグイン用です +@msg a JavaScript plug-in makes no command calls JavaScript プラグインはコマンドを呼び出しません +@msg vc.progress(done, total) takes two numbers vc.progress(done, total) には数値を 2 つ指定します +@msg vc.log(level, text) takes a level, 0 (error), 1 (warning), 2 (information) or 3 (debug), and a string vc.log(level, text) にはレベル 0 (エラー)、1 (警告)、2 (情報)、3 (デバッグ) のいずれかと文字列を指定します @msg the plug-in's grant can't be removed from the plug-in store プラグインの許可をプラグインストアから削除できません @msg permission `{shown}` is reserved for a later plug-in API; this host doesn't grant it 権限 `{shown}` は今後のプラグイン API 用に予約されています。このホストはこの権限を付与しません @msg unknown permission `{shown}` 不明な権限 `{shown}` diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index 8eeacee621..89c3327db7 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -9594,6 +9594,21 @@ axis Y Axis Y ღერძი @msg time budget დროის ბიუჯეტი @msg memory budget (the selection is too large to hand over) მეხსიერების ბიუჯეტი (მონიშნული ზედმეტად დიდია გადასაცემად) @msg output size ({what} is {len} bytes, limit {max}) გამოტანის ზომა ({what}: {len} ბაიტი, ლიმიტი {max}) +@msg {reason} ({id}, {script} line {line}, column {column}) {reason} ({id}, {script}, სტრიქონი {line}, სვეტი {column}) +@msg {reason} ({id}, {script}) {reason} ({id}, {script}) +@msg memory budget მეხსიერების ბიუჯეტი +@msg call depth გამოძახების სიღრმე +@msg run(input, params) returned no output object run(input, params)-მა გამოტანის ობიექტი არ დააბრუნა +@msg `runtime` "js" needs `script`: the name of the plug-in's .js file, next to the manifest `runtime` "js" საჭიროებს `script`-ს: პლაგინის .js ფაილის სახელს მანიფესტის გვერდით +@msg `script` must be the name of a .js file in the manifest's folder: 1-128 bytes, no folder, no `:`, not starting with `.` `script` უნდა იყოს მანიფესტის საქაღალდეში მყოფი .js ფაილის სახელი: 1-128 ბაიტი, საქაღალდის გარეშე, `:` სიმბოლოს გარეშე, `.` სიმბოლოთი არ უნდა იწყებოდეს +@msg `source` is the script's text, given only in the JSON that plugin.install's dataBase64 takes: a .vcplugin file names its script in `script` `source` სკრიპტის ტექსტია და მიეთითება მხოლოდ JSON-ში, რომელსაც plugin.install-ის dataBase64 იღებს: .vcplugin ფაილი თავის სკრიპტს `script` გასაღებში ასახელებს +@msg a JavaScript plug-in's manifest gives `runtime` "js" JavaScript პლაგინის მანიფესტი მიუთითებს `runtime` "js" +@msg `runtime` "js" is for an object filter (`kind` "filter"), not `kind` "{kind}" `runtime` "js" ობიექტების ფილტრისთვისაა (`kind` "filter"), არა `kind` "{kind}" მნიშვნელობისთვის +@msg a JavaScript plug-in can't list the permission `{name}`: of the host's permissions it may list `progress` JavaScript პლაგინს არ შეუძლია ნებართვის `{name}` ჩამოთვლა: ჰოსტის ნებართვებიდან მას შეუძლია ჩამოთვალოს `progress` +@msg a WebAssembly module's manifest leaves `runtime` out: "js" is for a JavaScript plug-in WebAssembly მოდულის მანიფესტი გამოტოვებს `runtime` გასაღებს: "js" JavaScript პლაგინისთვისაა +@msg a JavaScript plug-in makes no command calls JavaScript პლაგინი ბრძანებებს არ იძახებს +@msg vc.progress(done, total) takes two numbers vc.progress(done, total) იღებს ორ რიცხვს +@msg vc.log(level, text) takes a level, 0 (error), 1 (warning), 2 (information) or 3 (debug), and a string vc.log(level, text) იღებს დონეს, 0 (შეცდომა), 1 (გაფრთხილება), 2 (ინფორმაცია) ან 3 (გამართვა), და სტრიქონს @msg the plug-in's grant can't be removed from the plug-in store პლაგინის ნებართვის წაშლა პლაგინების საცავიდან შეუძლებელია @msg permission `{shown}` is reserved for a later plug-in API; this host doesn't grant it ნებართვა `{shown}` დაჯავშნილია პლაგინების მომავალი API-სთვის; ეს ჰოსტი მას არ გასცემს @msg unknown permission `{shown}` უცნობი ნებართვა `{shown}` diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index 57e0b8be10..5a064784a6 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -7085,6 +7085,21 @@ axis Y Axis Y축 @msg time budget 시간 예산 @msg memory budget (the selection is too large to hand over) 메모리 예산(선택 항목이 너무 커서 넘길 수 없음) @msg output size ({what} is {len} bytes, limit {max}) 출력 크기({what}: {len}바이트, 제한 {max}) +@msg {reason} ({id}, {script} line {line}, column {column}) {reason}({id}, {script} {line}행 {column}열) +@msg {reason} ({id}, {script}) {reason}({id}, {script}) +@msg memory budget 메모리 예산 +@msg call depth 호출 깊이 +@msg run(input, params) returned no output object run(input, params)이 출력 개체를 반환하지 않았습니다 +@msg `runtime` "js" needs `script`: the name of the plug-in's .js file, next to the manifest `runtime` "js"에는 `script`가 필요합니다: 매니페스트 옆에 있는 플러그인 .js 파일의 이름 +@msg `script` must be the name of a .js file in the manifest's folder: 1-128 bytes, no folder, no `:`, not starting with `.` `script`는 매니페스트 폴더에 있는 .js 파일의 이름이어야 합니다: 1-128바이트, 폴더 없음, `:` 없음, `.`으로 시작하지 않음 +@msg `source` is the script's text, given only in the JSON that plugin.install's dataBase64 takes: a .vcplugin file names its script in `script` `source`는 스크립트의 텍스트이며 plugin.install의 dataBase64가 받는 JSON에서만 지정합니다: .vcplugin 파일은 스크립트를 `script`에 지정합니다 +@msg a JavaScript plug-in's manifest gives `runtime` "js" JavaScript 플러그인의 매니페스트는 `runtime` "js"를 지정합니다 +@msg `runtime` "js" is for an object filter (`kind` "filter"), not `kind` "{kind}" `runtime` "js"는 개체 필터(`kind` "filter")용이며 `kind` "{kind}"용이 아닙니다 +@msg a JavaScript plug-in can't list the permission `{name}`: of the host's permissions it may list `progress` JavaScript 플러그인은 권한 `{name}`을(를) 나열할 수 없습니다: 호스트 권한 중에서 `progress`를 나열할 수 있습니다 +@msg a WebAssembly module's manifest leaves `runtime` out: "js" is for a JavaScript plug-in WebAssembly 모듈의 매니페스트는 `runtime`을 생략합니다: "js"는 JavaScript 플러그인용입니다 +@msg a JavaScript plug-in makes no command calls JavaScript 플러그인은 명령을 호출하지 않습니다 +@msg vc.progress(done, total) takes two numbers vc.progress(done, total)는 숫자 두 개를 받습니다 +@msg vc.log(level, text) takes a level, 0 (error), 1 (warning), 2 (information) or 3 (debug), and a string vc.log(level, text)는 수준 0(오류), 1(경고), 2(정보), 3(디버그) 중 하나와 문자열을 받습니다 @msg the plug-in's grant can't be removed from the plug-in store 플러그인 저장소에서 플러그인의 권한을 제거할 수 없습니다 @msg permission `{shown}` is reserved for a later plug-in API; this host doesn't grant it `{shown}` 권한은 이후 플러그인 API용으로 예약되어 있습니다. 이 호스트는 이 권한을 부여하지 않습니다 @msg unknown permission `{shown}` 알 수 없는 권한 `{shown}` diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index 5ed5cdc3e0..d0cc11abfd 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -549,6 +549,21 @@ liquify-list-end {0}, {1} {0} en {1} @msg time budget tijdbudget @msg memory budget (the selection is too large to hand over) geheugenbudget (de selectie is te groot om door te geven) @msg output size ({what} is {len} bytes, limit {max}) uitvoergrootte ({what} is {len} bytes, limiet {max}) +@msg {reason} ({id}, {script} line {line}, column {column}) {reason} ({id}, {script} regel {line}, kolom {column}) +@msg {reason} ({id}, {script}) {reason} ({id}, {script}) +@msg memory budget geheugenbudget +@msg call depth aanroepdiepte +@msg run(input, params) returned no output object run(input, params) heeft geen uitvoerobject teruggegeven +@msg `runtime` "js" needs `script`: the name of the plug-in's .js file, next to the manifest `runtime` "js" heeft `script` nodig: de naam van het .js-bestand van de plug-in, naast het manifest +@msg `script` must be the name of a .js file in the manifest's folder: 1-128 bytes, no folder, no `:`, not starting with `.` `script` moet de naam zijn van een .js-bestand in de map van het manifest: 1-128 bytes, geen map, geen `:`, niet beginnend met `.` +@msg `source` is the script's text, given only in the JSON that plugin.install's dataBase64 takes: a .vcplugin file names its script in `script` `source` is de tekst van het script en staat alleen in de JSON die dataBase64 van plugin.install aanneemt: een .vcplugin-bestand noemt zijn script in `script` +@msg a JavaScript plug-in's manifest gives `runtime` "js" het manifest van een JavaScript-plug-in geeft `runtime` "js" +@msg `runtime` "js" is for an object filter (`kind` "filter"), not `kind` "{kind}" `runtime` "js" is voor een objectfilter (`kind` "filter"), niet voor `kind` "{kind}" +@msg a JavaScript plug-in can't list the permission `{name}`: of the host's permissions it may list `progress` een JavaScript-plug-in kan de toestemming `{name}` niet vermelden: van de toestemmingen van de host mag hij `progress` vermelden +@msg a WebAssembly module's manifest leaves `runtime` out: "js" is for a JavaScript plug-in het manifest van een WebAssembly-module laat `runtime` weg: "js" is voor een JavaScript-plug-in +@msg a JavaScript plug-in makes no command calls een JavaScript-plug-in roept geen opdrachten aan +@msg vc.progress(done, total) takes two numbers vc.progress(done, total) neemt twee getallen +@msg vc.log(level, text) takes a level, 0 (error), 1 (warning), 2 (information) or 3 (debug), and a string vc.log(level, text) neemt een niveau, 0 (fout), 1 (waarschuwing), 2 (informatie) of 3 (foutopsporing), en een tekenreeks @msg the plug-in's grant can't be removed from the plug-in store de toekenning van de plug-in kan niet uit de plug-inopslag worden verwijderd @msg permission `{shown}` is reserved for a later plug-in API; this host doesn't grant it machtiging `{shown}` is gereserveerd voor een latere plug-in-API; deze host kent haar niet toe @msg unknown permission `{shown}` onbekende machtiging `{shown}` diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index 74029133dc..bf7a4a1f2d 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -7346,6 +7346,21 @@ axis Y Axis Oś Y @msg time budget budżet czasu @msg memory budget (the selection is too large to hand over) budżet pamięci (zaznaczenie jest zbyt duże, aby je przekazać) @msg output size ({what} is {len} bytes, limit {max}) rozmiar wyjścia ({what} ma {len} bajtów, limit {max}) +@msg {reason} ({id}, {script} line {line}, column {column}) {reason} ({id}, {script} wiersz {line}, kolumna {column}) +@msg {reason} ({id}, {script}) {reason} ({id}, {script}) +@msg memory budget budżet pamięci +@msg call depth głębokość wywołań +@msg run(input, params) returned no output object run(input, params) nie zwróciła obiektu wyjściowego +@msg `runtime` "js" needs `script`: the name of the plug-in's .js file, next to the manifest `runtime` "js" wymaga `script`: nazwy pliku .js wtyczki obok manifestu +@msg `script` must be the name of a .js file in the manifest's folder: 1-128 bytes, no folder, no `:`, not starting with `.` `script` musi być nazwą pliku .js w folderze manifestu: 1-128 bajtów, bez folderu, bez `:`, nie może zaczynać się od `.` +@msg `source` is the script's text, given only in the JSON that plugin.install's dataBase64 takes: a .vcplugin file names its script in `script` `source` to tekst skryptu, podawany tylko w JSON, który przyjmuje dataBase64 polecenia plugin.install: plik .vcplugin podaje swój skrypt w `script` +@msg a JavaScript plug-in's manifest gives `runtime` "js" manifest wtyczki JavaScript podaje `runtime` "js" +@msg `runtime` "js" is for an object filter (`kind` "filter"), not `kind` "{kind}" `runtime` "js" jest dla filtra obiektów (`kind` "filter"), nie dla `kind` "{kind}" +@msg a JavaScript plug-in can't list the permission `{name}`: of the host's permissions it may list `progress` wtyczka JavaScript nie może wymienić uprawnienia `{name}`: spośród uprawnień hosta może wymienić `progress` +@msg a WebAssembly module's manifest leaves `runtime` out: "js" is for a JavaScript plug-in manifest modułu WebAssembly pomija `runtime`: "js" jest dla wtyczki JavaScript +@msg a JavaScript plug-in makes no command calls wtyczka JavaScript nie wywołuje poleceń +@msg vc.progress(done, total) takes two numbers vc.progress(done, total) przyjmuje dwie liczby +@msg vc.log(level, text) takes a level, 0 (error), 1 (warning), 2 (information) or 3 (debug), and a string vc.log(level, text) przyjmuje poziom, 0 (błąd), 1 (ostrzeżenie), 2 (informacja) lub 3 (debugowanie), oraz ciąg znaków @msg the plug-in's grant can't be removed from the plug-in store nie można usunąć uprawnienia wtyczki z magazynu wtyczek @msg permission `{shown}` is reserved for a later plug-in API; this host doesn't grant it uprawnienie `{shown}` jest zarezerwowane dla późniejszego API wtyczek; ten host go nie przyznaje @msg unknown permission `{shown}` nieznane uprawnienie `{shown}` diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index a1747af0b2..d530a13d66 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -7390,6 +7390,21 @@ axis Y Axis Eixo Y @msg time budget orçamento de tempo @msg memory budget (the selection is too large to hand over) orçamento de memória (a seleção é grande demais para ser entregue) @msg output size ({what} is {len} bytes, limit {max}) tamanho da saída ({what} tem {len} bytes, limite {max}) +@msg {reason} ({id}, {script} line {line}, column {column}) {reason} ({id}, {script} linha {line}, coluna {column}) +@msg {reason} ({id}, {script}) {reason} ({id}, {script}) +@msg memory budget orçamento de memória +@msg call depth profundidade de chamadas +@msg run(input, params) returned no output object run(input, params) não retornou nenhum objeto de saída +@msg `runtime` "js" needs `script`: the name of the plug-in's .js file, next to the manifest `runtime` "js" precisa de `script`: o nome do arquivo .js do plug-in, ao lado do manifesto +@msg `script` must be the name of a .js file in the manifest's folder: 1-128 bytes, no folder, no `:`, not starting with `.` `script` deve ser o nome de um arquivo .js na pasta do manifesto: 1-128 bytes, sem pasta, sem `:`, sem começar com `.` +@msg `source` is the script's text, given only in the JSON that plugin.install's dataBase64 takes: a .vcplugin file names its script in `script` `source` é o texto do script, dado só no JSON que o dataBase64 de plugin.install recebe: um arquivo .vcplugin indica seu script em `script` +@msg a JavaScript plug-in's manifest gives `runtime` "js" o manifesto de um plug-in JavaScript indica `runtime` "js" +@msg `runtime` "js" is for an object filter (`kind` "filter"), not `kind` "{kind}" `runtime` "js" é para um filtro de objetos (`kind` "filter"), não para `kind` "{kind}" +@msg a JavaScript plug-in can't list the permission `{name}`: of the host's permissions it may list `progress` um plug-in JavaScript não pode listar a permissão `{name}`: das permissões do host, ele pode listar `progress` +@msg a WebAssembly module's manifest leaves `runtime` out: "js" is for a JavaScript plug-in o manifesto de um módulo WebAssembly omite `runtime`: "js" é para um plug-in JavaScript +@msg a JavaScript plug-in makes no command calls um plug-in JavaScript não chama comandos +@msg vc.progress(done, total) takes two numbers vc.progress(done, total) recebe dois números +@msg vc.log(level, text) takes a level, 0 (error), 1 (warning), 2 (information) or 3 (debug), and a string vc.log(level, text) recebe um nível, 0 (erro), 1 (aviso), 2 (informação) ou 3 (depuração), e uma string @msg the plug-in's grant can't be removed from the plug-in store a permissão do plug-in não pode ser removida do armazenamento de plug-ins @msg permission `{shown}` is reserved for a later plug-in API; this host doesn't grant it a permissão `{shown}` está reservada para uma API de plug-in futura; este host não a concede @msg unknown permission `{shown}` permissão desconhecida `{shown}` diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index ca0c8d5145..8131d30801 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -7113,6 +7113,21 @@ axis Y Axis Ось Y @msg time budget бюджет времени @msg memory budget (the selection is too large to hand over) бюджет памяти (выделение слишком велико для передачи) @msg output size ({what} is {len} bytes, limit {max}) размер вывода ({what}: {len} байт, предел {max}) +@msg {reason} ({id}, {script} line {line}, column {column}) {reason} ({id}, {script}, строка {line}, столбец {column}) +@msg {reason} ({id}, {script}) {reason} ({id}, {script}) +@msg memory budget бюджет памяти +@msg call depth глубина вызовов +@msg run(input, params) returned no output object run(input, params) не вернула объект вывода +@msg `runtime` "js" needs `script`: the name of the plug-in's .js file, next to the manifest для `runtime` "js" нужен `script`: имя файла .js модуля рядом с манифестом +@msg `script` must be the name of a .js file in the manifest's folder: 1-128 bytes, no folder, no `:`, not starting with `.` `script` должен быть именем файла .js в папке манифеста: 1-128 байт, без папки, без `:`, не начинаясь с `.` +@msg `source` is the script's text, given only in the JSON that plugin.install's dataBase64 takes: a .vcplugin file names its script in `script` `source` содержит текст скрипта и задаётся только в JSON, который принимает dataBase64 команды plugin.install: файл .vcplugin называет свой скрипт в `script` +@msg a JavaScript plug-in's manifest gives `runtime` "js" манифест модуля JavaScript задаёт `runtime` "js" +@msg `runtime` "js" is for an object filter (`kind` "filter"), not `kind` "{kind}" `runtime` "js" предназначен для фильтра объектов (`kind` "filter"), а не для `kind` "{kind}" +@msg a JavaScript plug-in can't list the permission `{name}`: of the host's permissions it may list `progress` модуль JavaScript не может перечислять разрешение `{name}`: из разрешений хоста он может перечислить `progress` +@msg a WebAssembly module's manifest leaves `runtime` out: "js" is for a JavaScript plug-in манифест модуля WebAssembly не указывает `runtime`: "js" предназначен для модуля JavaScript +@msg a JavaScript plug-in makes no command calls модуль JavaScript не вызывает команды +@msg vc.progress(done, total) takes two numbers vc.progress(done, total) принимает два числа +@msg vc.log(level, text) takes a level, 0 (error), 1 (warning), 2 (information) or 3 (debug), and a string vc.log(level, text) принимает уровень, 0 (ошибка), 1 (предупреждение), 2 (информация) или 3 (отладка), и строку @msg the plug-in's grant can't be removed from the plug-in store разрешение модуля нельзя удалить из хранилища модулей @msg permission `{shown}` is reserved for a later plug-in API; this host doesn't grant it разрешение `{shown}` зарезервировано для будущего API модулей; этот хост его не выдаёт @msg unknown permission `{shown}` неизвестное разрешение `{shown}` diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index c26474cf93..4992e4bbaa 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -9673,6 +9673,21 @@ digits Hindi Hindi @msg outlineText {v}: true or false outlineText {v}: true eller false @msg output intent profile: {e} profil för utgångsavsikt: {e} @msg output size ({what} is {len} bytes, limit {max}) utdatastorlek ({what} är {len} byte, gräns {max}) +@msg {reason} ({id}, {script} line {line}, column {column}) {reason} ({id}, {script} rad {line}, kolumn {column}) +@msg {reason} ({id}, {script}) {reason} ({id}, {script}) +@msg memory budget minnesbudget +@msg call depth anropsdjup +@msg run(input, params) returned no output object run(input, params) returnerade inget utdataobjekt +@msg `runtime` "js" needs `script`: the name of the plug-in's .js file, next to the manifest `runtime` "js" kräver `script`: namnet på pluginets .js-fil bredvid manifestet +@msg `script` must be the name of a .js file in the manifest's folder: 1-128 bytes, no folder, no `:`, not starting with `.` `script` måste vara namnet på en .js-fil i manifestets mapp: 1-128 byte, ingen mapp, inget `:`, får inte börja med `.` +@msg `source` is the script's text, given only in the JSON that plugin.install's dataBase64 takes: a .vcplugin file names its script in `script` `source` är skriptets text och anges bara i den JSON som dataBase64 i plugin.install tar: en .vcplugin-fil namnger sitt skript i `script` +@msg a JavaScript plug-in's manifest gives `runtime` "js" manifestet för ett JavaScript-plugin anger `runtime` "js" +@msg `runtime` "js" is for an object filter (`kind` "filter"), not `kind` "{kind}" `runtime` "js" är för ett objektfilter (`kind` "filter"), inte `kind` "{kind}" +@msg a JavaScript plug-in can't list the permission `{name}`: of the host's permissions it may list `progress` ett JavaScript-plugin kan inte ange behörigheten `{name}`: av värdens behörigheter får det ange `progress` +@msg a WebAssembly module's manifest leaves `runtime` out: "js" is for a JavaScript plug-in manifestet för en WebAssembly-modul utelämnar `runtime`: "js" är för ett JavaScript-plugin +@msg a JavaScript plug-in makes no command calls ett JavaScript-plugin anropar inga kommandon +@msg vc.progress(done, total) takes two numbers vc.progress(done, total) tar två tal +@msg vc.log(level, text) takes a level, 0 (error), 1 (warning), 2 (information) or 3 (debug), and a string vc.log(level, text) tar en nivå, 0 (fel), 1 (varning), 2 (information) eller 3 (felsökning), och en sträng @msg output.destination: {_1} files are CMYK, and “{name}” is an RGB profile output.destination: {_1}-filer är CMYK, och ”{name}” är en RGB-profil @msg output.destination: {e} output.destination: {e} @msg output.destination: no RGB or CMYK profile is called “{name}” output.destination: ingen RGB- eller CMYK-profil heter ”{name}” diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index 82186ebcdd..92e81f713b 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -7563,6 +7563,21 @@ axis Y Axis Y ekseni @msg time budget zaman bütçesi @msg memory budget (the selection is too large to hand over) bellek bütçesi (seçim aktarılamayacak kadar büyük) @msg output size ({what} is {len} bytes, limit {max}) çıktı boyutu ({what}: {len} bayt, sınır {max}) +@msg {reason} ({id}, {script} line {line}, column {column}) {reason} ({id}, {script} satır {line}, sütun {column}) +@msg {reason} ({id}, {script}) {reason} ({id}, {script}) +@msg memory budget bellek bütçesi +@msg call depth çağrı derinliği +@msg run(input, params) returned no output object run(input, params) bir çıktı nesnesi döndürmedi +@msg `runtime` "js" needs `script`: the name of the plug-in's .js file, next to the manifest `runtime` "js" için `script` gerekir: eklentinin bildirimin yanındaki .js dosyasının adı +@msg `script` must be the name of a .js file in the manifest's folder: 1-128 bytes, no folder, no `:`, not starting with `.` `script`, bildirimin klasöründeki bir .js dosyasının adı olmalıdır: 1-128 bayt, klasör yok, `:` yok, `.` ile başlamaz +@msg `source` is the script's text, given only in the JSON that plugin.install's dataBase64 takes: a .vcplugin file names its script in `script` `source` betiğin metnidir ve yalnızca plugin.install komutunun dataBase64 parametresinin aldığı JSON içinde verilir: bir .vcplugin dosyası betiğini `script` içinde adlandırır +@msg a JavaScript plug-in's manifest gives `runtime` "js" bir JavaScript eklentisinin bildirimi `runtime` "js" verir +@msg `runtime` "js" is for an object filter (`kind` "filter"), not `kind` "{kind}" `runtime` "js" bir nesne filtresi içindir (`kind` "filter"), `kind` "{kind}" için değil +@msg a JavaScript plug-in can't list the permission `{name}`: of the host's permissions it may list `progress` bir JavaScript eklentisi `{name}` iznini listeleyemez: ana makinenin izinlerinden `progress` iznini listeleyebilir +@msg a WebAssembly module's manifest leaves `runtime` out: "js" is for a JavaScript plug-in bir WebAssembly modülünün bildirimi `runtime` anahtarını atlar: "js" bir JavaScript eklentisi içindir +@msg a JavaScript plug-in makes no command calls bir JavaScript eklentisi komut çağırmaz +@msg vc.progress(done, total) takes two numbers vc.progress(done, total) iki sayı alır +@msg vc.log(level, text) takes a level, 0 (error), 1 (warning), 2 (information) or 3 (debug), and a string vc.log(level, text) bir düzey, 0 (hata), 1 (uyarı), 2 (bilgi) veya 3 (hata ayıklama), ve bir dize alır @msg the plug-in's grant can't be removed from the plug-in store eklentinin izni eklenti deposundan kaldırılamıyor @msg permission `{shown}` is reserved for a later plug-in API; this host doesn't grant it `{shown}` izni sonraki bir eklenti API’si için ayrılmıştır; bu ana bilgisayar bu izni vermez @msg unknown permission `{shown}` bilinmeyen izin `{shown}` diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index de3329ef10..206f0471d9 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -7095,6 +7095,21 @@ axis Y Axis Вісь Y @msg time budget бюджет часу @msg memory budget (the selection is too large to hand over) бюджет пам’яті (виділення завелике для передавання) @msg output size ({what} is {len} bytes, limit {max}) розмір виводу ({what}: {len} байтів, межа {max}) +@msg {reason} ({id}, {script} line {line}, column {column}) {reason} ({id}, {script}, рядок {line}, стовпець {column}) +@msg {reason} ({id}, {script}) {reason} ({id}, {script}) +@msg memory budget бюджет пам’яті +@msg call depth глибина викликів +@msg run(input, params) returned no output object run(input, params) не повернула об’єкт виводу +@msg `runtime` "js" needs `script`: the name of the plug-in's .js file, next to the manifest для `runtime` "js" потрібен `script`: ім’я файлу .js модуля поруч із маніфестом +@msg `script` must be the name of a .js file in the manifest's folder: 1-128 bytes, no folder, no `:`, not starting with `.` `script` має бути ім’ям файлу .js у теці маніфесту: 1-128 байтів, без теки, без `:`, не починаючись із `.` +@msg `source` is the script's text, given only in the JSON that plugin.install's dataBase64 takes: a .vcplugin file names its script in `script` `source` містить текст скрипту й задається лише в JSON, який приймає dataBase64 команди plugin.install: файл .vcplugin називає свій скрипт у `script` +@msg a JavaScript plug-in's manifest gives `runtime` "js" маніфест модуля JavaScript задає `runtime` "js" +@msg `runtime` "js" is for an object filter (`kind` "filter"), not `kind` "{kind}" `runtime` "js" призначено для фільтра об’єктів (`kind` "filter"), а не для `kind` "{kind}" +@msg a JavaScript plug-in can't list the permission `{name}`: of the host's permissions it may list `progress` модуль JavaScript не може перелічувати дозвіл `{name}`: із дозволів хоста він може перелічити `progress` +@msg a WebAssembly module's manifest leaves `runtime` out: "js" is for a JavaScript plug-in маніфест модуля WebAssembly не вказує `runtime`: "js" призначено для модуля JavaScript +@msg a JavaScript plug-in makes no command calls модуль JavaScript не викликає команд +@msg vc.progress(done, total) takes two numbers vc.progress(done, total) приймає два числа +@msg vc.log(level, text) takes a level, 0 (error), 1 (warning), 2 (information) or 3 (debug), and a string vc.log(level, text) приймає рівень, 0 (помилка), 1 (попередження), 2 (інформація) або 3 (налагодження), і рядок @msg the plug-in's grant can't be removed from the plug-in store дозвіл модуля не вдається вилучити зі сховища модулів @msg permission `{shown}` is reserved for a later plug-in API; this host doesn't grant it дозвіл `{shown}` зарезервовано для пізнішого API модулів; цей хост його не надає @msg unknown permission `{shown}` невідомий дозвіл `{shown}` diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index 675143a8d6..0cd610dfff 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -7142,6 +7142,21 @@ axis Y Axis Trục Y @msg time budget ngân sách thời gian @msg memory budget (the selection is too large to hand over) ngân sách bộ nhớ (vùng chọn quá lớn để chuyển giao) @msg output size ({what} is {len} bytes, limit {max}) kích thước đầu ra ({what} là {len} byte, giới hạn {max}) +@msg {reason} ({id}, {script} line {line}, column {column}) {reason} ({id}, {script} dòng {line}, cột {column}) +@msg {reason} ({id}, {script}) {reason} ({id}, {script}) +@msg memory budget ngân sách bộ nhớ +@msg call depth độ sâu lời gọi +@msg run(input, params) returned no output object run(input, params) không trả về đối tượng đầu ra nào +@msg `runtime` "js" needs `script`: the name of the plug-in's .js file, next to the manifest `runtime` "js" cần `script`: tên tệp .js của plug-in, nằm cạnh manifest +@msg `script` must be the name of a .js file in the manifest's folder: 1-128 bytes, no folder, no `:`, not starting with `.` `script` phải là tên một tệp .js trong thư mục của manifest: 1-128 byte, không có thư mục, không có `:`, không bắt đầu bằng `.` +@msg `source` is the script's text, given only in the JSON that plugin.install's dataBase64 takes: a .vcplugin file names its script in `script` `source` là văn bản của tập lệnh, chỉ được cung cấp trong JSON mà dataBase64 của plugin.install nhận: tệp .vcplugin nêu tên tập lệnh của nó trong `script` +@msg a JavaScript plug-in's manifest gives `runtime` "js" manifest của plug-in JavaScript cho `runtime` "js" +@msg `runtime` "js" is for an object filter (`kind` "filter"), not `kind` "{kind}" `runtime` "js" dành cho bộ lọc đối tượng (`kind` "filter"), không phải `kind` "{kind}" +@msg a JavaScript plug-in can't list the permission `{name}`: of the host's permissions it may list `progress` plug-in JavaScript không thể liệt kê quyền `{name}`: trong các quyền của máy chủ, nó có thể liệt kê `progress` +@msg a WebAssembly module's manifest leaves `runtime` out: "js" is for a JavaScript plug-in manifest của mô-đun WebAssembly bỏ qua `runtime`: "js" dành cho plug-in JavaScript +@msg a JavaScript plug-in makes no command calls plug-in JavaScript không gọi lệnh +@msg vc.progress(done, total) takes two numbers vc.progress(done, total) nhận hai số +@msg vc.log(level, text) takes a level, 0 (error), 1 (warning), 2 (information) or 3 (debug), and a string vc.log(level, text) nhận một mức, 0 (lỗi), 1 (cảnh báo), 2 (thông tin) hoặc 3 (gỡ lỗi), và một chuỗi @msg the plug-in's grant can't be removed from the plug-in store không thể xóa quyền của plug-in khỏi kho plug-in @msg permission `{shown}` is reserved for a later plug-in API; this host doesn't grant it quyền `{shown}` được dành cho một API plug-in sau này; máy chủ này không cấp quyền đó @msg unknown permission `{shown}` quyền không xác định `{shown}` diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index 57f6a4403b..35316805ae 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -7323,6 +7323,21 @@ axis Y Axis Y 轴 @msg time budget 时间预算 @msg memory budget (the selection is too large to hand over) 内存预算(所选内容太大,无法传递) @msg output size ({what} is {len} bytes, limit {max}) 输出大小({what} 为 {len} 字节,上限 {max}) +@msg {reason} ({id}, {script} line {line}, column {column}) {reason}({id},{script} 第 {line} 行,第 {column} 列) +@msg {reason} ({id}, {script}) {reason}({id},{script}) +@msg memory budget 内存预算 +@msg call depth 调用深度 +@msg run(input, params) returned no output object run(input, params) 未返回输出对象 +@msg `runtime` "js" needs `script`: the name of the plug-in's .js file, next to the manifest `runtime` "js" 需要 `script`:清单旁边增效工具 .js 文件的名称 +@msg `script` must be the name of a .js file in the manifest's folder: 1-128 bytes, no folder, no `:`, not starting with `.` `script` 必须是清单所在文件夹中 .js 文件的名称:1-128 字节,不含文件夹,不含 `:`,不以 `.` 开头 +@msg `source` is the script's text, given only in the JSON that plugin.install's dataBase64 takes: a .vcplugin file names its script in `script` `source` 是脚本的文本,只在 plugin.install 的 dataBase64 接受的 JSON 中给出:.vcplugin 文件在 `script` 中指定其脚本 +@msg a JavaScript plug-in's manifest gives `runtime` "js" JavaScript 增效工具的清单指定 `runtime` "js" +@msg `runtime` "js" is for an object filter (`kind` "filter"), not `kind` "{kind}" `runtime` "js" 用于对象滤镜(`kind` "filter"),而不是 `kind` "{kind}" +@msg a JavaScript plug-in can't list the permission `{name}`: of the host's permissions it may list `progress` JavaScript 增效工具不能列出权限 `{name}`:在主机的权限中,它可以列出 `progress` +@msg a WebAssembly module's manifest leaves `runtime` out: "js" is for a JavaScript plug-in WebAssembly 模块的清单省略 `runtime`:"js" 用于 JavaScript 增效工具 +@msg a JavaScript plug-in makes no command calls JavaScript 增效工具不调用命令 +@msg vc.progress(done, total) takes two numbers vc.progress(done, total) 接受两个数字 +@msg vc.log(level, text) takes a level, 0 (error), 1 (warning), 2 (information) or 3 (debug), and a string vc.log(level, text) 接受一个级别(0(错误)、1(警告)、2(信息)或 3(调试))和一个字符串 @msg the plug-in's grant can't be removed from the plug-in store 无法从增效工具存储中移除该增效工具的授权 @msg permission `{shown}` is reserved for a later plug-in API; this host doesn't grant it 权限 `{shown}` 保留给以后的增效工具 API;此主机不授予该权限 @msg unknown permission `{shown}` 未知权限 `{shown}` diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index 9834c17ea6..9c9e5c3009 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -7144,6 +7144,21 @@ axis Y Axis Y 軸 @msg time budget 時間預算 @msg memory budget (the selection is too large to hand over) 記憶體預算(所選內容太大,無法傳遞) @msg output size ({what} is {len} bytes, limit {max}) 輸出大小({what} 為 {len} 位元組,上限 {max}) +@msg {reason} ({id}, {script} line {line}, column {column}) {reason}({id},{script} 第 {line} 行,第 {column} 欄) +@msg {reason} ({id}, {script}) {reason}({id},{script}) +@msg memory budget 記憶體預算 +@msg call depth 呼叫深度 +@msg run(input, params) returned no output object run(input, params) 未傳回輸出物件 +@msg `runtime` "js" needs `script`: the name of the plug-in's .js file, next to the manifest `runtime` "js" 需要 `script`:資訊清單旁增效模組 .js 檔案的名稱 +@msg `script` must be the name of a .js file in the manifest's folder: 1-128 bytes, no folder, no `:`, not starting with `.` `script` 必須是資訊清單所在資料夾中 .js 檔案的名稱:1-128 位元組,不含資料夾,不含 `:`,不以 `.` 開頭 +@msg `source` is the script's text, given only in the JSON that plugin.install's dataBase64 takes: a .vcplugin file names its script in `script` `source` 是指令碼的文字,只在 plugin.install 的 dataBase64 接受的 JSON 中提供:.vcplugin 檔案在 `script` 中指定其指令碼 +@msg a JavaScript plug-in's manifest gives `runtime` "js" JavaScript 增效模組的資訊清單指定 `runtime` "js" +@msg `runtime` "js" is for an object filter (`kind` "filter"), not `kind` "{kind}" `runtime` "js" 用於物件濾鏡(`kind` "filter"),而不是 `kind` "{kind}" +@msg a JavaScript plug-in can't list the permission `{name}`: of the host's permissions it may list `progress` JavaScript 增效模組不能列出權限 `{name}`:在主機的權限中,它可以列出 `progress` +@msg a WebAssembly module's manifest leaves `runtime` out: "js" is for a JavaScript plug-in WebAssembly 模組的資訊清單不填寫 `runtime`:"js" 用於 JavaScript 增效模組 +@msg a JavaScript plug-in makes no command calls JavaScript 增效模組不呼叫命令 +@msg vc.progress(done, total) takes two numbers vc.progress(done, total) 接受兩個數字 +@msg vc.log(level, text) takes a level, 0 (error), 1 (warning), 2 (information) or 3 (debug), and a string vc.log(level, text) 接受一個層級(0(錯誤)、1(警告)、2(資訊)或 3(偵錯))和一個字串 @msg the plug-in's grant can't be removed from the plug-in store 無法從增效模組存放區移除該增效模組的授權 @msg permission `{shown}` is reserved for a later plug-in API; this host doesn't grant it 權限 `{shown}` 保留給日後的增效模組 API;此主機不授予該權限 @msg unknown permission `{shown}` 未知權限 `{shown}` diff --git a/crates/ui-egui/src/io/open.rs b/crates/ui-egui/src/io/open.rs index 180c459453..70797c4a0a 100644 --- a/crates/ui-egui/src/io/open.rs +++ b/crates/ui-egui/src/io/open.rs @@ -20,9 +20,15 @@ pub fn open_bytes(app: &mut VectorcraftApp, name: &str, bytes: &[u8], path: Opti /// [`open_bytes`], a document opening with `document.open`'s params `p`. fn open_bytes_with(app: &mut VectorcraftApp, name: &str, bytes: &[u8], path: Option, p: &Value) -> Result { let opens = opens_as(name); - // A WebAssembly plug-in is installed. + // A plug-in is installed: a JavaScript plug-in's manifest by its path, which the script it + // names is read beside. Without a path the manifest's bytes alone are refused, since they hold + // no script (`vectorcraft_plugins::js::SOURCE_RULE`). if opens == Some(OpensAs::Plugin) { - let module = json!({"dataBase64": vectorcraft_format::base64_encode(bytes), "name": path.as_deref().unwrap_or(name)}); + let js = vectorcraft_plugins::registry::is_js_package(std::path::Path::new(name)); + let module = match path.as_deref() { + Some(path) if js => json!({ "path": path }), + _ => json!({"dataBase64": vectorcraft_format::base64_encode(bytes), "name": path.as_deref().unwrap_or(name)}), + }; return install_module(app, module).map(|_| Value::Null); } if opens == Some(OpensAs::ShortcutSet) { diff --git a/crates/ui-egui/src/tests/plugins.rs b/crates/ui-egui/src/tests/plugins.rs index 0a80254db0..13484b098a 100644 --- a/crates/ui-egui/src/tests/plugins.rs +++ b/crates/ui-egui/src/tests/plugins.rs @@ -720,3 +720,26 @@ fn installing_a_plugin_that_reports_progress_says_so() { assert_eq!(vectorcraft_plugins::registry::granted(id).map(|g| g.permissions.len()), Some(2)); app.run("plugin.remove", json!({"id": id})).unwrap(); } + +/// File › Open of a JavaScript plug-in's `.vcplugin` installs it with the script beside it. Without +/// a path (the web file picker), the manifest alone is refused, the error says how the script is +/// given, and nothing is installed. +#[test] +fn opening_a_javascript_manifest_installs_it_with_its_script() { + let mut app = app(); + let id = "test.ui.js.open"; + let dir = std::env::temp_dir().join(format!("vc-ui-js-open-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + let manifest = json!({"id": id, "name": "Open JS", "kind": "filter", "runtime": "js", "script": "open.js"}).to_string(); + let path = dir.join("open.vcplugin"); + std::fs::write(&path, &manifest).unwrap(); + std::fs::write(dir.join("open.js"), "function run(input) { return input; }").unwrap(); + let e = io::open_bytes(&mut app, "open.vcplugin", manifest.as_bytes(), None).unwrap_err(); + assert!(e.contains(vectorcraft_plugins::js::SOURCE_RULE), "{e}"); + assert!(vectorcraft_plugins::registry::get(id).is_none()); + io::open_bytes(&mut app, "open.vcplugin", manifest.as_bytes(), Some(path.display().to_string())).unwrap(); + std::fs::remove_dir_all(&dir).unwrap(); + assert_eq!(vectorcraft_plugins::registry::get(id).and_then(|p| p.script().map(str::to_string)).as_deref(), Some("open.js")); + app.run("plugin.remove", json!({"id": id})).unwrap(); +} diff --git a/docs/mcp.md b/docs/mcp.md index 3c577e0356..9cf6948dbd 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -13244,7 +13244,10 @@ them again at startup (`plugin.remove` deletes them there). A window or process while it changes it, so installs, removals, grants and plug-in settings from two of them do not mix; when the file can't be locked, `plugin.install` and `plugin.remove` fail and change nothing: `plugin.install {path | dataBase64}` installs one, `plugin.list` / `plugin.info {id}` describe them (parameters, -schema, defaults). An object filter runs on the selected paths and compound paths with `plugin.run {id, params}` (one +schema, defaults). An object filter may also be a JavaScript plug-in: a `.vcplugin` manifest with `"runtime": "js"` and +`script`, the `.js` file beside it, which `plugin.install {path}`, `plugin.inspect {path}` and `plugin.reload` read +together (`runtime` and `script` in its entry); it runs in an interpreter of its own with no file, command or clock +access ([plugins.md](plugins.md#javascript-filters)). An object filter runs on the selected paths and compound paths with `plugin.run {id, params}` (one undo step; it may change, delete or add objects, and the result is selected). A filter whose manifest lists `inputs` (`type`, `image`, `symbolInstance`; `inputs` in its `plugin.list` entry) also lists `doc.read` in its `permissions`, so installing it needs a person's approval. It is also given the selected objects of those kinds to read, in paint order from the diff --git a/docs/plugins.md b/docs/plugins.md index ab294db1ff..bab1544da9 100644 --- a/docs/plugins.md +++ b/docs/plugins.md @@ -20,6 +20,9 @@ There are four kinds of plug-in: paths and compound paths. File › Open lists their files, File › Open With lists the importers by name, and the host hands them the file's bytes. +An object filter may also be written in JavaScript, as a manifest and a `.js` file ([JavaScript +filters](#javascript-filters)). + This page is the contract for plug-in authors and the reference for the host (`crates/plugins`, the `plugin.*` commands in `crates/engine/src/cmd/plugin.rs`). @@ -27,14 +30,14 @@ in `crates/engine/src/cmd/plugin.rs`). | Command | Params | What it does | |---|---|---| -| `plugin.list` | `{}` | `{"plugins": [{id, name, version, kind, author, description, params, paramsSchema, effect?, format?, extensions?, budget?, commands?, commandAllowlist?, size, source, api, paintOutput?, permissions, hash, cacheBytes}], "folder": report}` (`api` is the manifest's [plug-in API level](#permissions); `budget: "heavy"` for a [heavy filter](#heavy-filters); `commands` lists its [commands](#commands); `commandAllowlist` lists the commands it may [call](#command-calls); `paintOutput: true` marks a [painted live effect](#painted-live-effects); `permissions` lists what it [may do](#permissions), `hash` is the module's SHA-256; `cacheBytes` is the size of its [cache](#settings-and-cache)) | +| `plugin.list` | `{}` | `{"plugins": [{id, name, version, kind, author, description, params, paramsSchema, effect?, format?, extensions?, budget?, commands?, commandAllowlist?, size, source, api, paintOutput?, permissions, hash, cacheBytes}], "folder": report}` (`api` is the manifest's [plug-in API level](#permissions); `budget: "heavy"` for a [heavy filter](#heavy-filters); `commands` lists its [commands](#commands); `commandAllowlist` lists the commands it may [call](#command-calls); `paintOutput: true` marks a [painted live effect](#painted-live-effects); `permissions` lists what it [may do](#permissions), `hash` is the module's SHA-256; `runtime: "js"` and `script` mark a [JavaScript filter](#javascript-filters); `cacheBytes` is the size of its [cache](#settings-and-cache)) | | `plugin.info` | `{"id"}` | One plug-in: the `plugin.list` entry plus `manifest`, `defaults` and `lastError` (a live effect's last failure). | | `plugin.run` | `{"id", "params"?: {…}, "ids"?: [...]}` (plug-in params may also be top-level keys) | Runs an object filter on the selection (or `ids`; an `ids` that is not a list of object ids is an error). One undo step; the result is selected, except the objects it locked or made guides. | -| `plugin.install` | `{"path": "/x/y.wasm"}` (desktop) or `{"dataBase64": "…", "name"?}`, `"replace"?: bool`, `"allowHeavy": bool = false`, `"grant"?: [permission]`, `"hash"?: "sha256 hex"` | Validates and installs a module; returns its `plugin.list` entry. The desktop app and `vectorcraft-cli` keep it in the `Plug-ins` folder next to the preferences, so it is installed again after a restart (#2541). A module with other bytes than the plug-in installed with its id, or, with none installed, one whose id has [settings and a cache](#settings-and-cache) in the `Plug-ins` folder, installs only with `replace: true`, once the user agreed; it takes that plug-in's place and gets its settings and cache. The same module installs again without `replace`, and `replace: false` refuses a module whose id is installed. A [heavy filter](#heavy-filters) installs only with `allowHeavy: true`. A plug-in whose manifest lists [permissions](#permissions) installs only when `grant` lists every one of them, unless a grant is already recorded for a module with the same SHA-256. A request's `grant` and `allowHeavy` are refused except in a session started with `vectorcraft-cli --allow-plugin-grants`. With `hash`, a module whose SHA-256 differs is refused. A module whose `commandAllowlist` lists a command no plug-in may call is refused; ids no command has are listed as `unknownCommands` ([command calls](#command-calls)). | +| `plugin.install` | `{"path": "/x/y.wasm"}` or a [JavaScript filter's](#javascript-filters) `.vcplugin` (desktop) or `{"dataBase64": "…", "name"?}`, `"replace"?: bool`, `"allowHeavy": bool = false`, `"grant"?: [permission]`, `"hash"?: "sha256 hex"` | Validates and installs a module; returns its `plugin.list` entry. The desktop app and `vectorcraft-cli` keep it in the `Plug-ins` folder next to the preferences, so it is installed again after a restart (#2541). A module with other bytes than the plug-in installed with its id, or, with none installed, one whose id has [settings and a cache](#settings-and-cache) in the `Plug-ins` folder, installs only with `replace: true`, once the user agreed; it takes that plug-in's place and gets its settings and cache. The same module installs again without `replace`, and `replace: false` refuses a module whose id is installed. A [heavy filter](#heavy-filters) installs only with `allowHeavy: true`. A plug-in whose manifest lists [permissions](#permissions) installs only when `grant` lists every one of them, unless a grant is already recorded for a module with the same SHA-256. A request's `grant` and `allowHeavy` are refused except in a session started with `vectorcraft-cli --allow-plugin-grants`. With `hash`, a module whose SHA-256 differs is refused. A module whose `commandAllowlist` lists a command no plug-in may call is refused; ids no command has are listed as `unknownCommands` ([command calls](#command-calls)). | | `plugin.inspect` | as `plugin.install`: `{"path"}` or `{"dataBase64", "name"?}` | Validates a module without installing it; returns the `plugin.list` entry it would have, plus `needsApproval` (true when installing it needs a person's approval), `needsReplace` (true when `plugin.install` needs `replace: true`), and the `commandAllowlist` ids no command has (`unknownCommands`) and those no plug-in may call (`refusedCommands`). | | `plugin.remove` | `{"id"}` | Uninstalls, and deletes it from the `Plug-ins` folder with its [settings and cache](#settings-and-cache). | | `plugin.clearCache` | `{"id"?}` | Deletes every entry in the [cache](#settings-and-cache) of plug-in `id`, or of every installed plug-in; settings stay. Returns `{"cleared": [id], "bytesFreed"}`. | -| `plugin.reload` | `{"path"?: "folder"}` (default: the preference folder) | Installs every `*.wasm` in a folder, the first 1,000 by file name; a bad module is reported and skipped, and so are an entry that is not a regular file, a heavy filter and a plug-in whose permissions the user hasn't granted (nobody was asked). Returns `{"folder", "loaded", "failed": [{file, error}], "leftOut"}`; `leftOut` counts the `*.wasm` files past the first 1,000, which were not tried. | +| `plugin.reload` | `{"path"?: "folder"}` (default: the preference folder) | Installs every `*.wasm` and `*.vcplugin` in a folder, the first 1,000 by file name; a bad module is reported and skipped, and so are an entry that is not a regular file, a heavy filter and a plug-in whose permissions the user hasn't granted (nobody was asked). Returns `{"folder", "loaded", "failed": [{file, error}], "leftOut"}`; `leftOut` counts the `*.wasm` and `*.vcplugin` files past the first 1,000, which were not tried. | Live effects are applied like any effect: `effect.apply {"effect": "plugin.", "params": {…}}`, edited with `effect.setParams`, listed by `effect.list` (menu `Effect › Plug-ins`) and baked by Object › Expand Appearance. @@ -877,6 +880,61 @@ and `wat::when_given` a plug-in whose output depends on whether its input or par in a live effect's geometry. `wat::reporting` and `wat::cooperating` build level 2 plug-ins that import the host functions. +## JavaScript filters + +An object filter may also be written in JavaScript (ECMAScript 5.1, the language VectorCraft's scripts use). The +plug-in is two files in one folder: a manifest, `.vcplugin`, and the `.js` file it names in `script`. + +```json +{"id": "org.example.tint", "name": "Tint Blue", "kind": "filter", "runtime": "js", "script": "tint.js", + "params": {"blue": {"type": "number", "min": 0, "max": 1, "default": 1}}} +``` + +```js +function run(input, params) { + return {objects: input.objects.map(function (o) { + return {id: o.id, fills: [{type: "solid", color: {model: "rgb", r: 0, g: 0, b: params.blue}}]}; + })}; +} +``` + +The manifest has the keys of a module's [manifest](#manifest), with `"runtime": "js"` and `script`, a file name of 1 to +128 bytes ending in `.js`, without a folder or `:`, and not starting with `.`. Left out, `runtime` is WebAssembly, so +existing modules load as before; a module's own manifest may not give `"js"`. A JavaScript plug-in is a filter (`kind` +`"filter"`), and of the host's [permissions](#permissions) it may list `progress` but not `settings`, `cache` or +`commands`, so it has no `commandAllowlist`. + +`plugin.install {path}` and `plugin.inspect {path}` take the `.vcplugin` file, and File › Open and `plugin.reload` +install it like a `.wasm` file. The host refuses a manifest without `script`, with `source`, or with a `runtime` other +than `"js"`, and refuses a manifest file over 64 KiB or a script over 8 MiB by its size before reading it; under +automation read roots the script must be inside them too. The host reads the two files into one JSON object, the +manifest with the script's text in `source`: `plugin.install {dataBase64}` takes that object, the `Plug-ins` folder keeps +it as the plug-in's file, and `hash` is its SHA-256, so a changed manifest or script needs a new approval. Installing +parses the script and runs none of it; a syntax error is an install error with its line and column. + +Each run gets a new interpreter with its own heap, so nothing one run defines or changes, the built-ins' prototypes +included, reaches the next. The script's top level runs, then `run(input, params)` is called with the parsed +[input](#input) and [parameters](#parameters), and what it returns is written as JSON and checked +as a module's [output](#output) is, before anything in the document changes. The global object holds the language's +built-ins and `vc`: + +| Member | What it is | +|---|---| +| `vc.input`, `vc.params` | The input and parameter JSON as text. | +| `vc.progress(done, total)` | As `vc_progress` ([host imports](#host-imports-api-level-2)); with `progress` only. | +| `vc.cancelled()` | `true` once the user cancelled or the time budget ran out; with `progress` only. | +| `vc.log(level, text)` | Writes a log line as `vc_log` does: `level` 0 (error) to 3 (debug), `true` when written and `false` when the run's log budget dropped it; with `progress` only. | + +The realm has no `$`, `File`, `Folder`, `app`, `#include` or other part of the script runner, no file, network or +command access, and no clock: `Date.now()` is `NaN`. A run gets a filter's instruction budget (one budget for the top +level and the call, plus the budget per byte of input) and wall-clock budget, checked between slices of 1,000,000 +instructions, where Cancel stops it too; its heap is at most the interpreter's default heap and the plug-in's memory cap (512 MiB), whichever is smaller, and +an input and parameters larger than an eighth of the heap fail the run with the memory-budget error for a selection +too large to hand over. A thrown error, a limit, a missing `run`, a result that is not an object JSON can write, or an +output larger than 64 MiB fails the run, and the document and undo history stay as they were. The error names the +plug-in, its script and, for an error in the script, the line and column, for example `plug-in exceeded its +instruction budget (org.example.tint, tint.js line 3, column 5)`. + ## Performance The interpreter costs roughly 10–100× native speed per instruction. Filters handle a selection in one call, so a diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 3da663c191..d4c37bce85 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -2678,6 +2678,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **A drag ended by a command with Real-time Drawing off:** when Undo, Redo, a filter that calls commands or a plug-in command that calls commands ends a drag whose preview Real-time Drawing off has not applied yet, the preview is applied first and kept as an undo step of its own, as releasing the drag keeps it; a preview that fails cancels the drag. The filter or plug-in command is then given the objects where the drag left them. Regressions: `crates/engine/src/tests/plugins.rs`, `crates/engine/src/tests/prefs.rs`. Scores and hours unchanged. - **The warning of a preview applied when a command ends a drag:** a preview that Real-time Drawing off left unapplied, and that Undo, Clear History or another command applies before it runs, keeps its warning: the command's result carries it as `previewWarning`, and as `warning` when the command has none of its own, and the status bar shows it, as releasing the drag shows it. Typing kept as its own step when a tool's drag begins, or when Cmd lends the Selection tool, shows its applied preview's warning in the status bar too. Regressions: `settling_a_deferred_preview_keeps_its_warning` and `settling_typing_for_a_tool_shows_its_preview_warning` in `crates/engine/src/tests/prefs.rs`, `settled_warnings_join_the_result` in `crates/engine/src/session/execute.rs`. Scores and hours unchanged. - **Typing kept when a dialog or a panel previews, with Real-time Drawing off:** a dialog's Preview, a panel's live slider, the Effect Gallery's preview, the font menus' preview, a paint for the characters the Type tool selected and an inline graphic inserted while typing first apply the typing that Real-time Drawing off left unapplied, as an undo step of its own, and the status bar shows that typing's preview warning. The Character, Paragraph and Tabs panels, Bullets and Numbering, Justification and the inline graphic then act on the characters the Type tool selected in the typed text. When the typing can't be kept, the status bar shows the error and the dialog's preview does not start. Regressions: `settling_typing_for_a_dialog_returns_its_preview_warning` in `crates/engine/src/tests/prefs.rs`, `ending_deferred_typing_for_another_edit_keeps_the_typing` in `crates/engine/src/tests/textedit.rs`, `inserting_while_deferred_typing_keeps_the_typing` in `crates/engine/src/tests/inline.rs`, `settled_typing_tests` in `crates/ui-egui/src/dialogs/form.rs`, `stack_preview_keeps_typing_in_progress` in `crates/ui-egui/src/dialogs/effect_gallery.rs`. Scores and hours unchanged. +- **JavaScript filter plug-ins (G17, #2193):** an object filter may be a `.vcplugin` manifest with `"runtime": "js"` and the `.js` file its `script` names, installed with `plugin.install {path}` or from the plug-in folder. Each run gets a new interpreter with the filter's instruction, time and memory budgets and no file, command or clock access; `run(input, params)` returns the output a module would, checked the same way, and the document changes as one undo step. A manifest without `script`, an unsafe script name or a script over 8 MiB is refused before the script is read. Regressions: `crates/plugins/src/js.rs`, `crates/plugins/src/registry.rs`, `crates/engine/tests/plugin_js.rs`. Scores and hours unchanged. - **Plug-in progress, Cancel and log lines (G17):** at plug-in API level 2 a plug-in with the `progress` permission imports `env.vc_progress`, `env.vc_cancelled` and `env.vc_log`. A heavy filter's and an export's progress windows show its progress as a percentage bar, their Cancel reaches it through `vc_cancelled`, a light filter with `progress` and no `commandAllowlist` runs in the background with the same progress window when it runs at once or OK runs it with Preview off, and its log lines go to the app's log with its id, capped per line and per run. Installing checks every import and names the one it refuses. Regressions: `crates/plugins/src/host.rs`, `crates/plugins/tests/abi.rs`, `crates/engine/src/tests/plugins.rs`, `crates/engine/tests/plugin_fuzz.rs`, `crates/ui-egui/src/tests/plugin_runs.rs`. Scores and hours unchanged. - **Live-effect plug-ins paint their output (G17, #121):** a live effect whose manifest has `"api": 2` and `"paintOutput": true` returns pieces, each drawn by itself in order with fills and strokes of its own in the filter's paint forms (a piece without them keeps the object's; an empty list paints none; an effect on a fill returns only fills, one on a stroke only strokes). The whole result is checked first: limits, numbers in range with nothing clamped, known keys only, and the swatches and patterns it names in the document; one fault draws that step of the stack unchanged, keeps the effect record and puts the plug-in's name and the field in `plugin.info`'s `lastError`. The pieces are drawn, measured and exported to PDF and SVG from the appearance stack without changing the document, and Expand Appearance writes them as ordinary paths in one undo step. Effects without the key behave as before. Regressions: `crates/plugins/src/painted/tests.rs`, `crates/plugins/src/manifest.rs`, `crates/engine/src/tests/plugins.rs`, `crates/engine/tests/plugin_fuzz.rs`. Scores and hours unchanged. - **Painted effects refuse gradient stop plates without a spot link (G17):** a gradient stop with process `plates` in a painted live effect's fill or stroke must link to a spot swatch of the document itself; a stop with no link, a `null` link or only the gradient's own `swatch` refuses the whole result, and so does a link to a process swatch or Registration, also when a cached result's swatch stops being a spot swatch. `lastError` names the stop's `plates`. Regressions: `crates/plugins/src/painted/tests.rs`, `crates/plugins/src/effect.rs` (`cached_painted_plates_refuse_after_spot_becomes_process`). Scores and hours unchanged. From d73d0c0f9b9c4924484cbc31fc787e22fa90f66e Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 22 Nov 2026 11:27:41 -0800 Subject: [PATCH 064/151] JavaScript: a yield reserves only the heap its saved frame takes A yield reserved room for every finally entry on the interpreter, those of the frames under the generator's included, and for the result it hands back, while the saved frame keeps only its own operands and entries. Under deep callers in finally blocks a yield could stop at the heap limit with enough room for its frame. It now reserves what the saved frame keeps. The tests check the value a throw raises in a generator that has not started, and the fuel each call of a completed generator's next takes against a native method that takes none. docs/mcp.md and docs/target-app-parity.md say that an engine a .js script makes has Symbol and the iterators, and that one a .jsx script or a source string makes does not. The parity entry no longer says that spread is missing or that scripts call next() themselves. --- crates/js/src/generator.rs | 8 +++-- crates/js/src/generator_tests.rs | 53 ++++++++++++++++++++++++++++---- docs/mcp.md | 8 +++-- docs/target-app-parity.md | 2 +- 4 files changed, 59 insertions(+), 12 deletions(-) diff --git a/crates/js/src/generator.rs b/crates/js/src/generator.rs index 5169dcb2d0..c033a025d3 100644 --- a/crates/js/src/generator.rs +++ b/crates/js/src/generator.rs @@ -200,8 +200,12 @@ impl Interp { let result = iter_result(self, v, false)?; self.replace(1, result)?; } - let frame = self.frame()?; - let held = (self.stack.len().saturating_sub(frame.base)).saturating_add(self.finally_sites.len()).saturating_add(self.finally_marks.len()); + // What `save_frame` keeps: the frame's operands without the result, popped below, and its + // own `finally` entries, not those of the frames under it. + let base = self.frame()?.base; + let sites = self.finally_sites.len().saturating_sub(self.finally_sites.partition_point(|&(_, slot)| slot < base)); + let marks = self.finally_marks.iter().filter(|&&(_, _, slot)| slot >= base).count(); + let held = self.stack.len().saturating_sub(base.saturating_add(1)).saturating_add(sites).saturating_add(marks); let bytes = GENERATOR_BYTES.saturating_add(SLOT_BYTES.saturating_mul(held)); self.reserve_heap(bytes)?; let result = self.pop()?; diff --git a/crates/js/src/generator_tests.rs b/crates/js/src/generator_tests.rs index fcdd00033e..3eea94da23 100644 --- a/crates/js/src/generator_tests.rs +++ b/crates/js/src/generator_tests.rs @@ -100,7 +100,9 @@ fn throw_goes_into_a_suspended_generator() { e instanceof RangeError && it.next().done", ); // A generator that has not started is completed by `throw`, which its body never sees. - truth("var ran = false; function* g() { ran = true; } var it = g(); try { it.throw(1); } catch (e) {} !ran && it.next().done"); + truth( + "var ran = false; function* g() { ran = true; } var it = g(); var e; try { it.throw(1); } catch (x) { e = x; } e === 1 && !ran && it.next().done", + ); throws("function* g() {} var it = g(); it.next(); it.throw(new TypeError('after the end'));", "TypeError: after the end"); } @@ -275,6 +277,40 @@ fn an_unreachable_suspended_generator_is_freed() { assert!(freed + 1_000_000 < held, "held {held}, after {freed}"); } +/// The smallest heap limit, to within 256 bytes, under which `script` runs after `setup`. +fn smallest_heap_limit(setup: &str, script: &str) -> usize { + let fits = |limit: usize| { + let mut realm = es2015(Limits::default()); + assert_eq!(realm.run(setup), Ok(JsValue::Number(0.0))); + realm.collect_garbage(); + realm.set_limits(Limits { heap_bytes: limit, ..Limits::default() }); + realm.run(script).is_ok() + }; + let (mut low, mut high) = (0, 64 << 20); + assert!(fits(high), "{script}"); + while high - low > 256 { + let mid = low + (high - low) / 2; + if fits(mid) { + high = mid; + } else { + low = mid; + } + } + high +} + +#[test] +fn a_yield_reserves_only_what_its_frame_keeps() { + // At the `yield` in `inside`, the 1,001 frames under the generator's are in `finally` blocks + // that a throw entered. Their entries stay with those frames, so the yield needs no more room + // than the one in `before`, which comes before those frames are pushed. + let setup = "function* g() { yield 1; } var it = g(); 0"; + let inside = "function f(n) { try { throw 0; } finally { if (n) f(n - 1); else it.next(); } } try { f(1000); } catch (e) {} 0"; + let before = "it.next(); function f(n) { try { throw 0; } finally { if (n) f(n - 1); } } try { f(1000); } catch (e) {} 0"; + let (inside, before) = (smallest_heap_limit(setup, inside), smallest_heap_limit(setup, before)); + assert!(inside < before + 4096, "inside {inside}, before {before}"); +} + #[test] fn generators_stay_within_the_limits() { let mut realm = es2015(Limits { fuel: 20_000, ..Limits::default() }); @@ -282,12 +318,17 @@ fn generators_stay_within_the_limits() { Err(RunError { kind: RunErrorKind::Limit(LimitKind::Fuel), .. }) => {} other => panic!("{other:?}"), } - // Each resumption takes fuel even when the body does no work. - let mut realm = es2015(Limits { fuel: 20_000, ..Limits::default() }); - match realm.run("var it = (function* () {})(); it.next(); while (true) it.next();") { - Err(RunError { kind: RunErrorKind::Limit(LimitKind::Fuel), .. }) => {} - other => panic!("{other:?}"), + // Each resumption takes fuel even when the generator has completed: 1,000 calls of its `next` + // take at least 1,000 more than the same calls of a native method that takes none. + let mut realm = es2015(Limits::default()); + let setup = "var it = (function* () {})(); it.next(); var control = { next: Object.prototype.valueOf }; 0"; + assert_eq!(realm.run(setup), Ok(JsValue::Number(0.0))); + let mut used = Vec::new(); + for callee in ["control", "it"] { + assert_eq!(realm.run(&format!("for (var i = 0; i < 1000; i++) {callee}.next(); 0")), Ok(JsValue::Number(0.0))); + used.push(Limits::default().fuel - realm.fuel_left()); } + assert!(used[1] >= used[0] + 1000, "{used:?}"); // A deep `yield*` chain stops at the frame limit, and the realm can run again. let mut realm = es2015(Limits { frames: 200, ..Limits::default() }); match realm.run("function* d(n) { if (n) yield* d(n - 1); else yield 1; } d(1000).next();") { diff --git a/docs/mcp.md b/docs/mcp.md index c720283975..0e674ee2e3 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2661,9 +2661,11 @@ app through the global object `vc`, and writes to the Script Console and runs ot - `vc.args` gives a read-only copy of the `args` object each time it is read. - `vc.api.version` is `"1.0"`, and `vc.api.has(feature)` says whether the API has a feature. -A script does not have `Symbol` or the iterators of arrays, strings and `arguments` objects: `typeof Symbol` is -`"undefined"`, and `Array.prototype.values`, `keys` and `entries` are not defined. The JavaScript engine's ECMAScript -2015 mode (`Options::es2015` in `vectorcraft-js`) adds them, as `docs/target-app-parity.md` describes. +An engine that a `.js` script makes runs in the JavaScript engine's ECMAScript 2015 mode (`Options::es2015` in +`vectorcraft-js`) and has `Symbol` and the iterators of arrays, strings and `arguments` objects, as +`docs/target-app-parity.md` describes. An engine that a `.jsx` script or a `source` string makes does not have them: +`typeof Symbol` is `"undefined"`, and `Array.prototype.values`, `keys` and `entries` are not defined. An engine that +`#targetengine` keeps holds the built-ins of the run that made it, whichever kind of script runs in it later. Before any of the script runs, its preprocessor lines are read. The help page https://extendscript.docsforadobe.dev/extendscript-tools-features/preprocessor-directives/ describes these lines, and diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 177831817e..e72bb9817a 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1083,7 +1083,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - `vectorcraft-js` provides the ECMAScript 5.1 built-ins `Object` with its property-descriptor functions, `create`, `keys`, `seal` and `freeze` (section 15.2), `Function.prototype.bind` (15.3.4.5), `Array` with every ES5 method (15.4), the error types (15.11), `Math` (15.8), `JSON` with revivers, replacers and indentation (15.12), and the global functions with Annex B's `escape` and `unescape` (15.1, B.2). The array methods work on array-like objects. A method visits only the indices that exist when its range is longer than 4,096 indices and more than 8 times the properties on the object and its prototypes, so `new Array(4294967295).join("")` ends at once; a shorter range is visited index by index, holes included, and each index takes fuel. `join` writes a cycle back to an array as an empty string, `JSON.stringify` throws a `TypeError` on a cycle, and deep `JSON` nesting uses no native stack. Every loop takes fuel and every result is checked against the heap limit. `cargo xtask test262` runs the suite's ES5 built-in tests that need only these built-ins: 6,798 of 6,866 runs pass (the 34 failing tests expect rules of later editions). It also fetches the `json2.js` polyfill at a pinned commit and checks that its `stringify` and `parse` agree with the built-in `JSON`. Tests: `crates/js/src/builtins_tests.rs`, `crates/js/tests/test262.rs`, `crates/js/tests/json2.rs`. - `vectorcraft-js` has `String`, `Number`, `RegExp` and `Date` as ECMAScript 5.1 defines them (sections 15.5, 15.7, 15.9 and 15.10, https://262.ecma-international.org/5.1/), with Annex B's `substr`, `getYear`, `setYear` and `toGMTString`. `toFixed`, `toExponential` and `toPrecision` format a number from its exact decimal value, and `toString(radix)` writes any base from 2 to 36. Regular expressions (flags `g`, `i` and `m`) run on a backtracking matcher whose choice points and capture state count against the heap limit and which takes fuel for every step, so a catastrophic pattern stops at the fuel limit and 50,000 nested groups give a `SyntaxError` at the default depth limit. A string method that would build a string past the heap limit stops before it allocates. `Date` reads the clock and time zone the host sets (`Realm::set_clock`, `Realm::set_time_zone`; local time is UTC by default). `cargo xtask test262` runs the suite's `built-ins` tests for the four (https://github.com/tc39/test262): of the runs of the ES5 tests that need only the built-ins present, 1,379 of 1,411 pass for `String`, 298 of 298 for `Number`, 954 of 988 for `RegExp` and 8 of 8 for `Date`. The others expect later editions' rules (built-in functions whose `length` can be deleted, flags given with a RegExp object, a negative `lastIndex`, `RegExp.prototype` as a plain object, and `RegExp.prototype`'s `global`, `ignoreCase` and `multiline` properties that can be deleted). Tests: `crates/js/src/text_tests.rs`, `crates/js/tests/test262.rs`. - `cargo xtask test262` also reads the suite's Annex B tests (https://tc39.es/ecma262/#sec-additional-ecmascript-features-for-web-browsers), whichever edition they name. It parses the 819 tests under `test/annexB/language` without a feature tag in the modes their flags give, so a `for`-`in` variable with an initializer must parse in sloppy code and give a `SyntaxError` in strict code (682 of 843 runs pass), and it runs those tests and the `test/annexB/built-ins` tests for `String`, `Date`, `RegExp` and `Function` that need only the built-ins present (263 of 667 runs pass for the language tests and 56 of 252 for the built-ins). Failures go to `annexb-parse-failures.txt`, `annexb-language-failures.txt` and `annexb-builtins-failures.txt` beside the suite. A conformance failure does not fail the tests, but an interpreter panic fails `annex_b_runs`, so `cargo xtask test262` exits non-zero. A folder or file the runner cannot read also fails the test that reads it. The runner reads only regular files inside the suite, up to 8 MiB each, and does not follow symbolic links. Tests: `crates/js/tests/test262.rs`. - - With `Options::es2015` set, which it is not by default, a `vectorcraft-js` realm also has `Symbol` (ECMA-262 11th edition, section 19.4, https://262.ecma-international.org/11.0/): `Symbol(description)`, which `new` refuses with a `TypeError`, the `description` getter, `toString`, `valueOf`, and `Symbol.for` and `Symbol.keyFor` over a registry that lasts as long as the realm. `typeof` gives `"symbol"`. Symbols are property keys: `Object.getOwnPropertySymbols` lists an object's Symbol keys in the order they were added, `Object.defineProperty`, `getOwnPropertyDescriptor`, `freeze`, `seal`, `in`, `delete` and `hasOwnProperty` take them, and `for`-`in`, `Object.keys`, `Object.getOwnPropertyNames` and `JSON.stringify` leave them out. `String(symbol)` and `symbol.toString()` give `Symbol(description)`; any other conversion of a Symbol to a string or a number, such as `Symbol() + ''`, throws a `TypeError`. A string such as `'0b10'` or `'0o2'` converts to a number, as section 7.1.3.1 gives. The well-known Symbols `Symbol.iterator`, `Symbol.asyncIterator`, `Symbol.hasInstance`, `Symbol.toPrimitive` and `Symbol.toStringTag` are defined: conversion to a primitive calls an object's `@@toPrimitive` method, `instanceof` calls the right side's `@@hasInstance` method, and `Object.prototype.toString` writes a string `@@toStringTag`; `JSON.stringify` calls a String or Number object's `@@toPrimitive` method too. `Date.prototype[Symbol.toPrimitive]` (section 20.4.4.45) converts a Date with `toString` first for the hints `"string"` and `"default"` and with `valueOf` first for `"number"`, so `date + 1` joins the date's string; an object without an `@@toPrimitive` method, a Date whose method is `null` included, tries `valueOf` first when no hint is given. Nothing reads `Symbol.asyncIterator` yet. `Array.prototype.values` (also `Array.prototype[Symbol.iterator]`), `keys` and `entries`, `String.prototype[Symbol.iterator]` and every `arguments` object's `Symbol.iterator` return iterators whose `next()` gives `{value, done}` objects; a string iterator steps by code point and keeps a surrogate pair together. An array iterator reads the `length` at each step, so it visits elements added during the walk. Each step takes fuel, as does each prototype a Symbol-keyed lookup passes, and each Symbol and registry entry counts against the heap limit. A realm without the option, including the one the app runs scripts in, has none of these names, and a host function that returns a Symbol there throws a `TypeError`. The language does not have `for`-`of`, spread or destructuring yet, so scripts call `next()` themselves. `cargo xtask test262` runs the suite's tests of `Symbol`, `ArrayIteratorPrototype`, `StringIteratorPrototype`, `Object.getOwnPropertySymbols`, `Array.prototype.values`, `keys`, `entries` and `Symbol.iterator`, and `String.prototype[Symbol.iterator]` that need only these built-ins and parse as ES5, in such a realm: 164 of 216 runs pass (6 passed before), and the 52 others expect a configurable function `length` and a function `name` property. Tests: `crates/js/src/symbol_tests.rs`, `crates/js/tests/test262.rs`. + - With `Options::es2015` set, which it is not by default, a `vectorcraft-js` realm also has `Symbol` (ECMA-262 11th edition, section 19.4, https://262.ecma-international.org/11.0/): `Symbol(description)`, which `new` refuses with a `TypeError`, the `description` getter, `toString`, `valueOf`, and `Symbol.for` and `Symbol.keyFor` over a registry that lasts as long as the realm. `typeof` gives `"symbol"`. Symbols are property keys: `Object.getOwnPropertySymbols` lists an object's Symbol keys in the order they were added, `Object.defineProperty`, `getOwnPropertyDescriptor`, `freeze`, `seal`, `in`, `delete` and `hasOwnProperty` take them, and `for`-`in`, `Object.keys`, `Object.getOwnPropertyNames` and `JSON.stringify` leave them out. `String(symbol)` and `symbol.toString()` give `Symbol(description)`; any other conversion of a Symbol to a string or a number, such as `Symbol() + ''`, throws a `TypeError`. A string such as `'0b10'` or `'0o2'` converts to a number, as section 7.1.3.1 gives. The well-known Symbols `Symbol.iterator`, `Symbol.asyncIterator`, `Symbol.hasInstance`, `Symbol.toPrimitive` and `Symbol.toStringTag` are defined: conversion to a primitive calls an object's `@@toPrimitive` method, `instanceof` calls the right side's `@@hasInstance` method, and `Object.prototype.toString` writes a string `@@toStringTag`; `JSON.stringify` calls a String or Number object's `@@toPrimitive` method too. `Date.prototype[Symbol.toPrimitive]` (section 20.4.4.45) converts a Date with `toString` first for the hints `"string"` and `"default"` and with `valueOf` first for `"number"`, so `date + 1` joins the date's string; an object without an `@@toPrimitive` method, a Date whose method is `null` included, tries `valueOf` first when no hint is given. Nothing reads `Symbol.asyncIterator` yet. `Array.prototype.values` (also `Array.prototype[Symbol.iterator]`), `keys` and `entries`, `String.prototype[Symbol.iterator]` and every `arguments` object's `Symbol.iterator` return iterators whose `next()` gives `{value, done}` objects; a string iterator steps by code point and keeps a surrogate pair together. An array iterator reads the `length` at each step, so it visits elements added during the walk. Each step takes fuel, as does each prototype a Symbol-keyed lookup passes, and each Symbol and registry entry counts against the heap limit. `script.run` makes the realm for a `.js` script with the option; a realm made without it, as for a `.jsx` script or a `source` string, has none of these names, and a host function that returns a Symbol there throws a `TypeError`. `yield*` reads an iterator through `Symbol.iterator`; spread does not, and reads values by the rule the entry on ECMAScript 2015 forms gives. The language does not have `for`-`of` or destructuring yet. `cargo xtask test262` runs the suite's tests of `Symbol`, `ArrayIteratorPrototype`, `StringIteratorPrototype`, `Object.getOwnPropertySymbols`, `Array.prototype.values`, `keys`, `entries` and `Symbol.iterator`, and `String.prototype[Symbol.iterator]` that need only these built-ins and parse as ES5, in such a realm: 164 of 216 runs pass (6 passed before), and the 52 others expect a configurable function `length` and a function `name` property. Tests: `crates/js/src/symbol_tests.rs`, `crates/js/tests/test262.rs`. - With `Options::es2015`, a `vectorcraft-js` realm also has generators (ECMA-262 11th edition, sections 14.4 and 25.4, https://262.ecma-international.org/11.0/): `function*` declarations and expressions, `*name() {…}` methods in object literals, `yield`, and `yield*`, which passes `next`, `throw` and `return` on to the iterator it delegates to and closes an iterator without `throw` before it throws a `TypeError`. A generator object's `next`, `return` and `throw` come from `%GeneratorPrototype%`, which inherits from `%IteratorPrototype%`; `return` runs the `finally` blocks around the `yield`, `throw` raises the value there, and resuming a generator while its body runs throws a `TypeError`. `%GeneratorFunction%` builds a generator function from source as `Function` does, and is reached through a generator function's `constructor`. A generator function is not a constructor. In sloppy code outside a generator function's body and parameters, `yield` stays an identifier, and a realm without the option reads `function*` as a syntax error. A suspended generator keeps its frame and operands in its object, which the collector keeps while the object is reachable and frees with it. A resumption pushes that frame on the interpreter's frame stack and takes fuel, so a generator driven from a script uses no native stack, and a deep `yield*` chain stops at the frame limit. A realm made without the option that reads the syntax later has no generator built-ins, and calling a generator function there throws a `TypeError`. `script.run` runs generators in a `.js` script. `cargo xtask test262` runs the suite's tests under `language/statements/generators`, `language/expressions/generators`, `language/expressions/yield`, `built-ins/GeneratorPrototype` and `built-ins/GeneratorFunction` that need only the built-ins present, in such a realm: 509 of 549 runs of 296 tests pass (94 of 96 runs of 50 tests passed before), and the 40 others expect a configurable function `length`, a function `name` property and the `caller` and `arguments` restrictions. Tests: `crates/js/src/generator_tests.rs`, `crates/js/tests/test262.rs`, `crates/engine/src/tests/script_run.rs`. - Scripts: `cargo xtask corpus --scripts` fetches 397 public scripts and 1 file they include from 19 MIT and Apache-2.0 repositories at pinned commits into `corpus/scripts` (gitignored), each repository's license file beside its scripts. `xtask/script-corpus.txt` lists every file with its size and SHA-256, and a download is checked against both before it replaces anything; one more candidate is left out because it is over the 1 MiB limit for one script. `cargo xtask scripts --pass-rate [--report ]` runs each script headless in a process of its own (a new document, 5,000,000 instructions, no dialog answers, file reads only in its repository's folder and a new folder of its own, file writes only in that folder, no command it can start, stopped after 10 seconds) and writes a JSON report: the pass rate overall, per repository and for the scripts without dialogs or windows, how many parse, and each script's outcome. Script failures never fail the command, and without the corpus it skips. These limits are VectorCraft's own. Tests: `xtask/src/script_corpus.rs`, `crates/engine/tests/script_corpus.rs`. - With `Options::e4x` set, an E4X name standing alone (`@a`, `@ns::a`, `@[expr]`, `ns::a`, `*`) inside `with` or a filter predicate can be assigned, with `=` or a compound operator, incremented, decremented, deleted and used as a `for` or `for each` variable, as well as read. Each of these uses the nearest XML or XMLList value in scope that holds the name and evaluates the name once. When no XML value in scope holds the name, the read or write throws a `ReferenceError` before the right-hand side runs and creates no child or attribute, as ECMA-357 section 11.1 (https://ecma-international.org/publications-and-standards/standards/ecma-357/) specifies, so a filter such as `list.(@id == '1')` throws when an item has no `@id` and no outer XML value holds one. Tests: `crates/js/src/xml_tests.rs`. From 2e9040d01b38840f7522b26bc4442d204eed9677 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 22 Nov 2026 11:09:43 -0800 Subject: [PATCH 065/151] Canvas: a press moved and released in one frame drags the tool A tool press that moves and goes up in the same frame now gets a Drag at the release position before its Up, as a held press does, so the Rectangle tool draws the rectangle instead of opening its dialog at the press point. A press that does not move stays a click. - A tool that builds a stroke from the drag's samples gets the frame's moves between the press and the button-up, not the hover moves before the press. - The Zoom tool's marquee for such a press reads only the frame's events between the press and the button-up, with Space as it was at the press: Space and moves after the release no longer shift it. - The press starts its gesture, and its Down goes, with the modifiers, Space and Backtick held at the press, not those held at the end of the frame. Space held at the press and let go before the release pans. - A pan or a turn of the view pressed and released in one frame follows the pointer to the release, and Shift held at the release snaps the turn. --- crates/ui-egui/src/canvas/drag.rs | 44 +++++- crates/ui-egui/src/canvas/input.rs | 136 ++++++++++++++---- crates/ui-egui/src/canvas/tests.rs | 217 ++++++++++++++++++++++++++++- 3 files changed, 365 insertions(+), 32 deletions(-) diff --git a/crates/ui-egui/src/canvas/drag.rs b/crates/ui-egui/src/canvas/drag.rs index 45b474c6d4..9aadc14f3d 100644 --- a/crates/ui-egui/src/canvas/drag.rs +++ b/crates/ui-egui/src/canvas/drag.rs @@ -134,6 +134,18 @@ pub(super) fn backquote_at_release(ui: &Ui, button: egui::PointerButton, before: /// Whether `key` was held when `button` went up in this frame, by the rules of /// [`backquote_at_release`], with `before` its state at the end of the frame before. pub(super) fn key_at_release(ui: &Ui, key: egui::Key, button: egui::PointerButton, before: Option) -> bool { + key_at_button(ui, key, button, false, before) +} + +/// Whether `key` was held when `button` went down in this frame, by the rules of +/// [`backquote_at_release`] with the button-down in place of the button-up. +pub(super) fn key_at_press(ui: &Ui, key: egui::Key, button: egui::PointerButton, before: Option) -> bool { + key_at_button(ui, key, button, true, before) +} + +/// Whether `key` was held when `button` first went down (`pressed`) or up in this frame +/// ([`key_at_release`], [`key_at_press`]). +fn key_at_button(ui: &Ui, key: egui::Key, button: egui::PointerButton, pressed: bool, before: Option) -> bool { ui.input(|i| { let now = i.key_down(key); // A press or release of `key` (`Some(pressed)`), or a focus loss (`None`). @@ -142,7 +154,9 @@ pub(super) fn key_at_release(ui: &Ui, key: egui::Key, button: egui::PointerButto egui::Event::WindowFocused(false) => Some(None), _ => None, }; - let Some(up) = i.events.iter().position(|e| matches!(e, egui::Event::PointerButton { button: b, pressed: false, .. } if *b == button)) else { + let Some(up) = + i.events.iter().position(|e| matches!(e, egui::Event::PointerButton { button: b, pressed: p, .. } if *b == button && *p == pressed)) + else { return now; }; let start = match i.events.iter().find_map(step) { @@ -218,9 +232,30 @@ pub(super) type FrameMove = (Pos2, Option, Option); /// button's button-up in this frame, if it came: the moves after it are hover, and the button-up's /// position is the pointer's. The last move before it is left out only when it is at that /// position; its tilt and rotation come second either way. +#[cfg(test)] pub(super) fn frame_moves(ui: &Ui, stylus: Option<&StylusFeed>, release: Option) -> (Vec, Option) { + frame_moves_since(ui, stylus, release, false) +} + +/// [`frame_moves`], and with `since_press` only the moves after the primary button first went down +/// in this frame: a press that began in this frame did not pass the positions before it. +pub(super) fn frame_moves_since( + ui: &Ui, + stylus: Option<&StylusFeed>, + release: Option, + since_press: bool, +) -> (Vec, Option) { let samples = stylus.map(StylusFeed::take_moves).unwrap_or_default(); ui.input(|i| { + // How many of the frame's moves came before the press, when only those after it count. + let before_press = if since_press { + i.events + .iter() + .position(|e| matches!(e, egui::Event::PointerButton { button: egui::PointerButton::Primary, pressed: true, .. })) + .map_or(0, |k| i.events.iter().take(k).filter(|e| matches!(e, egui::Event::PointerMoved(_))).count()) + } else { + 0 + }; // How many of the frame's moves came before the button-up, and where it came, if it came. let before_up = release.and_then(|b| { i.events.iter().enumerate().find_map(|(k, e)| match e { @@ -264,6 +299,7 @@ pub(super) fn frame_moves(ui: &Ui, stylus: Option<&StylusFeed>, release: Option< } None => moves.pop().and_then(|(_, _, q)| q), }; + moves.drain(..before_press.min(moves.len())); // A burst of events (a stalled frame) is thinned to a bounded count. const MAX: usize = 64; if moves.len() > MAX { @@ -279,10 +315,10 @@ pub(super) fn frame_moves(ui: &Ui, stylus: Option<&StylusFeed>, release: Option< /// for the others, which get one drag a frame. The moves are read either way, so the host's feed /// pairs the next frame's with its own. The tilt and rotation the feed kept for the pointer's /// position come second, for every tool. With `released`, only the moves before the primary -/// button-up count. -pub(super) fn tool_frame_moves(ui: &Ui, app: &VectorcraftApp, released: bool) -> (Vec, Option) { +/// button-up count, and with `pressed_here` too, only those after the press in this frame. +pub(super) fn tool_frame_moves(ui: &Ui, app: &VectorcraftApp, released: bool, pressed_here: bool) -> (Vec, Option) { let release = released.then_some(egui::PointerButton::Primary); - let (moves, last_pose) = frame_moves(ui, app.services.stylus.as_ref(), release); + let (moves, last_pose) = frame_moves_since(ui, app.services.stylus.as_ref(), release, pressed_here); (if app.session.tool_wants_samples() { moves } else { vec![] }, last_pose) } diff --git a/crates/ui-egui/src/canvas/input.rs b/crates/ui-egui/src/canvas/input.rs index a4ca1863c0..20550efe25 100644 --- a/crates/ui-egui/src/canvas/input.rs +++ b/crates/ui-egui/src/canvas/input.rs @@ -1,8 +1,8 @@ use super::artboards::{artboard_name_at, begin_artboard_name_edit, name_press_id, select_named_artboard}; use super::drag::{ FrameMove, HoverContext, apply_requests, backquote_at_release, backquote_seen, dispatch, drag_art_out, drag_id, drag_layer_id, drag_pos_id, - drop_press, key_at_release, mods, move_pose, on_canvas, pen_pose, pen_pressure, space_lends_view_tools, space_seen, tool_drag_doc_id, - tool_drag_mods_changed, tool_drag_moved, tool_frame_moves, tool_holds, tool_press_doc_id, + drop_press, key_at_press, key_at_release, mods, move_pose, on_canvas, pen_pose, pen_pressure, space_lends_view_tools, space_seen, + tool_drag_doc_id, tool_drag_mods_changed, tool_drag_moved, tool_frame_moves, tool_holds, tool_press_doc_id, }; use super::view::{ HOLD_DELAY, HOLD_ZOOM, SCRUB_SLOP, SCRUB_ZOOM, WheelTurn, animated_zoom, edge_scroll, edge_scroll_pixels, pan_pixels, pan_ppp, rotate_about, @@ -122,12 +122,29 @@ pub(super) fn handle_input(app: &mut VectorcraftApp, ui: &Ui, resp: &egui::Respo } else { // Pressed and released in this frame (a quick click or tap): the press starts where the // button went down, not where the pointer moved to after the release, and ends now, with - // the modifiers, Space and position of its release, not those of the next frame. + // the modifiers, Space and position of its release, not those of the next frame. It + // starts, and its Down goes, with the modifiers, Space and Backtick held at the press, + // not those held at the release or after it. let released = !pointer.primary_down(); - let start = if released { press_pos(ui, egui::PointerButton::Primary).filter(|q| rect.contains(*q)).unwrap_or(p) } else { p }; - begin_drag(app, ui, &f, start); + let primary = egui::PointerButton::Primary; + let start = if released { press_pos(ui, primary).filter(|q| rect.contains(*q)).unwrap_or(p) } else { p }; + let (press, backquote) = if released { + let m = press_mods(ui, primary).unwrap_or(m); + let space = space_lends_view_tools(app, m, key_at_press(ui, egui::Key::Space, primary, f.space_before)); + (Pointing { m, space, ..f }, key_at_press(ui, egui::Key::Backtick, primary, backquote_before)) + } else { + (Pointing { ..f }, backquote_now) + }; + begin_drag(app, ui, &press, start, backquote); if released && let Some(d) = ui.data(|dd| dd.get_temp::(drag_id())) { - end_drag(app, ui, &f, d, egui::PointerButton::Primary, start); + // A pan or a turn of the view follows the pointer to where the button went up, with + // the modifiers held then (Shift snaps the turn). + if matches!(d, Drag::Pan { .. } | Drag::RotateView { .. }) + && let Some(up) = release_pos(ui, primary, false) + { + drag_held(app, ui, &Pointing { m: release_mods(ui, primary).unwrap_or(m), ..press }, d, up); + } + end_drag(app, ui, &f, d, egui::PointerButton::Primary, start, true); } } } else if drag.is_none() @@ -148,7 +165,7 @@ pub(super) fn handle_input(app: &mut VectorcraftApp, ui: &Ui, resp: &egui::Respo if held { drag_held(app, ui, &f, d, p); } else { - end_drag(app, ui, &f, d, button, p); + end_drag(app, ui, &f, d, button, p, false); } } else if let Some(p) = hover_tool // A press on an artboard's name starts no drag: the moves while it is held are not hover. @@ -330,8 +347,9 @@ fn present_step(app: &mut VectorcraftApp, ui: &Ui, f: &Pointing, drag: Option { - let start = zoom_marquee_start(ui, start, before, p); + let start = zoom_marquee_start(ui, start, before, p, None); ui.data_mut(|dd| dd.insert_temp(drag_id(), Drag::ZoomBox { start })); marquee(ui.painter(), egui::Rect::from_two_pos(start, p)); } @@ -483,7 +501,7 @@ fn drag_held(app: &mut VectorcraftApp, ui: &Ui, f: &Pointing, d: Drag, p: Pos2) // or the web, a finger) and a macOS pen's moves carry their own pressure; a // mouse's, a pen's on X11 among them, take the host's latest. Other tools get // the last position only, so a costly drag preview runs once a frame. - let (moves, last_pose) = tool_frame_moves(ui, app, false); + let (moves, last_pose) = tool_frame_moves(ui, app, false, false); // Held near an edge of the canvas, the drag scrolls the view so it can go on past // what shows (#8551). The moves above came before the scroll and keep the view they // were made in; the pointer's position takes the scrolled one, so the tool gets a @@ -599,16 +617,21 @@ fn dispatch_frame_moves(app: &mut VectorcraftApp, ui: &Ui, f: &Pointing, backquo /// A gesture whose `button` went up ends where it went up, with the modifiers and Space held then: /// the moves and key changes after the release in this frame do not count. Without a release in -/// this frame, it ends at `p` with the modifiers and Space held now. -fn end_drag(app: &mut VectorcraftApp, ui: &Ui, f: &Pointing, d: Drag, button: egui::PointerButton, p: Pos2) { +/// this frame, it ends at `p` with the modifiers and Space held now. `pressed_here` says that the +/// gesture was pressed in this frame too ([`drag_released`]). +fn end_drag(app: &mut VectorcraftApp, ui: &Ui, f: &Pointing, d: Drag, button: egui::PointerButton, p: Pos2, pressed_here: bool) { let m = release_mods(ui, button).unwrap_or(f.m); let space = space_lends_view_tools(app, m, key_at_release(ui, egui::Key::Space, button, f.space_before)); let up = Pointing { m, space, ..*f }; - drag_released(app, ui, &up, d, release_pos(ui, button, false).unwrap_or(p)); + let cut = if pressed_here { press_span(ui, button) } else { None }; + drag_released(app, ui, &up, d, release_pos(ui, button, false).unwrap_or(p), cut); } -/// A gesture released at `p`: the view settles, or the tool gets its up. -fn drag_released(app: &mut VectorcraftApp, ui: &Ui, f: &Pointing, d: Drag, p: Pos2) { +/// A gesture released at `p`: the view settles, or the tool gets its up. With `cut`, the gesture +/// was pressed in this frame, and `cut` holds the indexes of the frame's events between its press +/// and its button-up ([`press_span`]): a press that moved away from where it went down dragged, and the +/// Zoom tool's marquee takes only those events. +fn drag_released(app: &mut VectorcraftApp, ui: &Ui, f: &Pointing, d: Drag, p: Pos2, cut: Option>) { let Pointing { resp, rect, m, space, xf, view, .. } = *f; // The last position the tool's drag got: none if the press never dragged. let last_drag: Option = ui.data(|dd| dd.get_temp(tool_drag_doc_id())); @@ -628,7 +651,7 @@ fn drag_released(app: &mut VectorcraftApp, ui: &Ui, f: &Pointing, d: Drag, p: Po let ui_zoom = app.canvas_ui_zoom; match d { Drag::ZoomBox { start } => { - let start = zoom_marquee_start(ui, start, before, p); + let start = zoom_marquee_start(ui, start, before, p, cut); ui.data_mut(|dd| dd.remove::(zoom_space_free_id())); let r = egui::Rect::from_two_pos(start, p); if let Some(vm) = app.view_mut() { @@ -664,8 +687,17 @@ fn drag_released(app: &mut VectorcraftApp, ui: &Ui, f: &Pointing, d: Drag, p: Po // button-up: the moves after it are hover. A modifier that changed at the release // with the pointer held still reshapes the preview too, as it does while held // (#4711): Shift pressed in the release's frame still draws a square. - let (moves, last_pose) = tool_frame_moves(ui, app, true); + let (moves, last_pose) = tool_frame_moves(ui, app, true, cut.is_some()); let pen = move_pose(app, &xf, last_pose); + // Pressed and released in this frame: the press dragged when it went up, or moved + // before it went up, away from the press, as a held press drags on any move + // ([`tool_drag_moved`]). The tools keep a click's jitter a click themselves. + let dragged_here = cut.as_ref().is_some_and(|r| { + ui.input(|i| { + let Some(egui::Event::PointerButton { pos: q, .. }) = r.start.checked_sub(1).and_then(|k| i.events.get(k)) else { return false }; + *q != p || i.events.get(r.clone()).unwrap_or_default().iter().any(|e| matches!(e, egui::Event::PointerMoved(at) if at != q)) + }) + }); if let Some(last) = last_drag { dispatch_frame_moves(app, ui, f, backquote, moves); if last != xf.to_doc(p) || mods_changed { @@ -679,6 +711,21 @@ fn drag_released(app: &mut VectorcraftApp, ui: &Ui, f: &Pointing, d: Drag, p: Po }; dispatch(app, &ev, view); } + } else if dragged_here { + // Pressed, moved and released in one frame: the press dragged to where it went + // up, so a Shape tool draws the shape instead of opening its dialog, and a tool + // that builds a stroke from the drag's samples gets the moves after the press + // first. + dispatch_frame_moves(app, ui, f, backquote, moves); + let ev = PointerEvent { + kind: PointerKind::Drag, + pos: xf.to_doc(p), + mods: mods(m, space), + backquote, + pressure: pen_pressure(ui, app, false), + pen, + }; + dispatch(app, &ev, view); } let ev = PointerEvent { kind: PointerKind::Up, @@ -779,6 +826,27 @@ fn press_pos(ui: &Ui, button: egui::PointerButton) -> Option { }) } +/// The modifiers held when `button` first went down in this frame ([`press_pos`]). +fn press_mods(ui: &Ui, button: egui::PointerButton) -> Option { + ui.input(|i| { + i.events.iter().find_map(|e| match e { + egui::Event::PointerButton { button: b, pressed: true, modifiers, .. } if *b == button => Some(*modifiers), + _ => None, + }) + }) +} + +/// The indexes of this frame's events after `button` first went down and before it next went up: +/// the events of a press that began and ended in this frame. `None` without both. +fn press_span(ui: &Ui, button: egui::PointerButton) -> Option> { + ui.input(|i| { + let is = |e: &egui::Event, down: bool| matches!(e, egui::Event::PointerButton { button: b, pressed, .. } if *b == button && *pressed == down); + let press = i.events.iter().position(|e| is(e, true))?; + let up = i.events.iter().skip(press).position(|e| is(e, false))?; + Some(press + 1..press + up) + }) +} + /// The modifiers held when `button` first went up in this frame, the release that ends a drag. fn release_mods(ui: &Ui, button: egui::PointerButton) -> Option { ui.input(|i| { @@ -802,29 +870,43 @@ fn zoom_space_free_id() -> egui::Id { /// moves and Space presses and releases are taken in the order they came, so each move follows the /// Space state it came with. The Space key counts as held whatever the modifiers, so a marquee that /// Cmd+Space started while the Type tool edits text follows the same rules once Cmd is let go. -fn zoom_marquee_start(ui: &Ui, start: Pos2, before: Option, p: Pos2) -> Pos2 { +/// With `cut`, the indexes of the frame's events between a press and a release that both came in +/// this frame ([`press_span`]), only those events count: Space pressed or released and moves made +/// after the button-up do not move the marquee. +fn zoom_marquee_start(ui: &Ui, start: Pos2, before: Option, p: Pos2, cut: Option>) -> Pos2 { enum Step { Space(bool), Move(Pos2), } let id = zoom_space_free_id(); - let (steps, space): (Vec, bool) = ui.input(|i| { + let (steps, space): (Vec<(usize, Step)>, bool) = ui.input(|i| { let steps = i .events .iter() - .filter_map(|e| match e { - egui::Event::Key { key: egui::Key::Space, pressed, repeat: false, .. } => Some(Step::Space(*pressed)), - egui::Event::PointerMoved(q) => Some(Step::Move(*q)), + .enumerate() + .filter_map(|(k, e)| match e { + egui::Event::Key { key: egui::Key::Space, pressed, repeat: false, .. } => Some((k, Step::Space(*pressed))), + egui::Event::PointerMoved(q) => Some((k, Step::Move(*q))), _ => None, }) .collect(); (steps, i.key_down(egui::Key::Space)) }); // Space as it was when the frame began: the opposite of its first press or release, else as it is now. - let mut held = steps.iter().find_map(|s| if let Step::Space(down) = s { Some(!down) } else { None }).unwrap_or(space); - let mut free = !held || ui.data(|d| d.get_temp::(id)).unwrap_or(true); + let mut held = steps.iter().find_map(|(_, s)| if let Step::Space(down) = s { Some(!down) } else { None }).unwrap_or(space); + // With `cut`, Space as it was at the press, and only the steps between the press and the button-up. + let (from, to) = cut.as_ref().map_or((0, usize::MAX), |r| (r.start, r.end)); + for (_, s) in steps.iter().filter(|(k, _)| *k < from) { + if let Step::Space(down) = s { + held = *down; + } + } + let steps = steps.into_iter().filter(|(k, _)| (from..to).contains(k)).map(|(_, s)| s); + // Space held at the press sizes the marquee until it is let go; the press set the flag with + // Space as it was at the end of the frame, so a press in this frame takes it from the press. + let mut free = !held || (cut.is_none() && ui.data(|d| d.get_temp::(id)).unwrap_or(true)); let (mut start, mut at) = (start, before); - for s in steps.into_iter().chain(std::iter::once(Step::Move(p))) { + for s in steps.chain(std::iter::once(Step::Move(p))) { match s { Step::Space(down) => { held = down; diff --git a/crates/ui-egui/src/canvas/tests.rs b/crates/ui-egui/src/canvas/tests.rs index e1a4260f03..9646093f6f 100644 --- a/crates/ui-egui/src/canvas/tests.rs +++ b/crates/ui-egui/src/canvas/tests.rs @@ -1614,6 +1614,220 @@ fn space_held_at_the_release_counts_when_the_focus_goes_after_it() { assert_eq!(lost, released, "a focus loss after the release keeps Space as held at the release"); } +/// A Rectangle tool press that moves and goes up in one frame drags to where it went up: it draws +/// the rectangle across the drag and opens no Rectangle dialog. One that moves no farther than the +/// tool's own click distance is a click, which opens the dialog. +#[test] +fn a_press_moved_and_released_within_one_frame_drags_the_tool() { + { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.session.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + app.select_tool("rectangle"); + let ctx = egui::Context::default(); + frame(&mut app, &ctx, vec![]); + let at = app.canvas_rect.unwrap().center(); + let jitter = at + vec2(2.0, 1.0); + let b = |pos, pressed| egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers: egui::Modifiers::NONE }; + frame(&mut app, &ctx, vec![egui::Event::PointerMoved(at)]); + frame(&mut app, &ctx, vec![b(at, true), egui::Event::PointerMoved(jitter), b(jitter, false)]); + frame(&mut app, &ctx, vec![]); + assert_eq!(app.ui.dialog.as_ref().map(|d| d.kind.as_str()), Some("rectangle"), "a click's jitter opens the dialog"); + assert!(app.session.active().unwrap().doc.layers[0].children().unwrap().is_empty(), "a click's jitter draws nothing"); + } + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.session.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + app.select_tool("rectangle"); + let ctx = egui::Context::default(); + frame(&mut app, &ctx, vec![]); + let from = app.canvas_rect.unwrap().center() - vec2(30.0, 15.0); + let to = from + vec2(60.0, 30.0); + let b = |pos, pressed| egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers: egui::Modifiers::NONE }; + frame(&mut app, &ctx, vec![egui::Event::PointerMoved(from)]); + frame(&mut app, &ctx, vec![b(from, true), egui::Event::PointerMoved(to), b(to, false)]); + frame(&mut app, &ctx, vec![]); + assert!(app.ui.dialog.is_none(), "the drag opens no dialog: {:?}", app.ui.dialog.as_ref().map(|d| &d.kind)); + let st = app.session.active().unwrap(); + let kids = st.doc.layers[0].children().unwrap(); + assert_eq!(kids.len(), 1, "the drag draws one rectangle"); + let r = kids[0].geometric_bounds().unwrap(); + let (w, h) = (r.width(), r.height()); + assert!(w > 0.0 && (w - 2.0 * h).abs() < 1e-6, "the rectangle spans the drag, got {w} x {h}"); +} + +/// With Animated Zoom off, a Zoom tool drag pressed and released in one frame zooms to the area +/// dragged across, though Space goes down, the pointer moves and Space goes up after the release in +/// that frame. +#[test] +fn space_after_a_zoom_drag_within_one_frame_does_not_move_its_marquee() { + use egui::Event; + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.session.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + app.run("prefs.set", json!({"key": "animatedZoom", "value": false})).unwrap(); + app.select_tool("zoom"); + let ctx = egui::Context::default(); + frame(&mut app, &ctx, vec![]); + let rect = app.canvas_rect.unwrap(); + let at = rect.center() - vec2(100.0, 50.0); + let to = at + vec2(100.0, 50.0); + let button = |pos, pressed| Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() }; + let space = |pressed| Event::Key { key: egui::Key::Space, physical_key: None, pressed, repeat: false, modifiers: Default::default() }; + let z0 = app.view().unwrap().zoom; + let area = z0 * f64::from((rect.width() / 100.0).min(rect.height() / 50.0)); + frame(&mut app, &ctx, vec![Event::PointerMoved(at)]); + frame( + &mut app, + &ctx, + vec![button(at, true), Event::PointerMoved(to), button(to, false), space(true), Event::PointerMoved(to + vec2(40.0, 20.0)), space(false)], + ); + frame(&mut app, &ctx, vec![]); + let z = app.view().unwrap().zoom; + assert!((z - area).abs() < 1e-6, "the drag zooms to its area: {z0} → {z}, not {area}"); + // Cmd+Space held at the press and Space let go before the release, in the press's frame: the + // moves while Space was held size the marquee, as they do over several frames. + app.view_mut().unwrap().zoom = z0; + let cmd = egui::Modifiers::COMMAND; + let button = |pos, pressed| Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers: cmd }; + let space = |pressed| Event::Key { key: egui::Key::Space, physical_key: None, pressed, repeat: false, modifiers: cmd }; + frame(&mut app, &ctx, vec![Event::ModifiersChanged(cmd), space(true), Event::PointerMoved(at)]); + frame( + &mut app, + &ctx, + vec![button(at, true), Event::PointerMoved(at + vec2(50.0, 25.0)), Event::PointerMoved(to), space(false), button(to, false)], + ); + frame(&mut app, &ctx, vec![Event::ModifiersChanged(egui::Modifiers::NONE)]); + let z = app.view().unwrap().zoom; + assert!((z - area).abs() < 1e-6, "Space held at the press sizes the marquee: {z0} → {z}, not {area}"); +} + +/// A Selection tool click pressed and released in one frame presses with the modifiers held at +/// its press: Shift held at the press and let go before the release adds the clicked object to +/// the selection. +#[test] +fn a_click_within_one_frame_presses_with_the_modifiers_of_its_press() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); + let a = app.run("shape.rectangle", json!({"x": 20, "y": 20, "width": 60, "height": 60})).unwrap()["id"].clone(); + let b = app.run("shape.rectangle", json!({"x": 200, "y": 100, "width": 60, "height": 60})).unwrap()["id"].clone(); + app.select_tool("selection"); + app.run("select.set", json!({"ids": [a]})).unwrap(); + let ctx = egui::Context::default(); + frame(&mut app, &ctx, vec![]); + let xf = Xf::new(app.canvas_rect.unwrap(), app.view().unwrap()); + let at = xf.to_screen(Point::new(230.0, 130.0)); + let press = |pressed, modifiers| egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers }; + frame(&mut app, &ctx, vec![egui::Event::PointerMoved(at)]); + frame( + &mut app, + &ctx, + vec![ + egui::Event::ModifiersChanged(egui::Modifiers::SHIFT), + press(true, egui::Modifiers::SHIFT), + egui::Event::ModifiersChanged(egui::Modifiers::NONE), + press(false, egui::Modifiers::NONE), + ], + ); + frame(&mut app, &ctx, vec![]); + let id = |v: &serde_json::Value| vectorcraft_doc::NodeId(v.as_u64().unwrap()); + let mut selected = app.session.active().unwrap().selection.objects.clone(); + selected.sort_by_key(|n| n.0); + assert_eq!(selected, vec![id(&a), id(&b)], "Shift held at the press adds the clicked object"); +} + +/// A press and release in one frame takes Space as it was at the press: Space held at the press +/// and let go before the release pans the view to the release instead of drawing with the +/// Rectangle tool, and Space pressed after the release leaves a Rectangle tool click, which opens +/// its dialog. +#[test] +fn a_press_within_one_frame_takes_space_as_it_was_at_the_press() { + let run = |events: &dyn Fn(Pos2, Pos2) -> Vec| { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.session.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + app.select_tool("rectangle"); + let ctx = egui::Context::default(); + frame(&mut app, &ctx, vec![]); + let at = app.canvas_rect.unwrap().center(); + frame(&mut app, &ctx, vec![egui::Event::PointerMoved(at)]); + let center = app.view().unwrap().center; + frame(&mut app, &ctx, events(at, at + vec2(60.0, 30.0))); + frame(&mut app, &ctx, vec![]); + let drawn = app.session.active().unwrap().doc.layers[0].children().unwrap().len(); + let panned = app.view().unwrap().center != center; + (drawn, app.ui.dialog.as_ref().map(|d| d.kind.clone()), panned) + }; + let b = |pos, pressed| egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers: egui::Modifiers::NONE }; + let space = |pressed| egui::Event::Key { key: egui::Key::Space, physical_key: None, pressed, repeat: false, modifiers: egui::Modifiers::NONE }; + let held = run(&|a, to| vec![space(true), b(a, true), egui::Event::PointerMoved(to), space(false), b(to, false)]); + assert_eq!(held, (0, None, true), "Space held at the press pans"); + let after = run(&|a, _| vec![b(a, true), b(a, false), space(true)]); + assert_eq!(after, (0, Some("rectangle".to_string()), false), "Space after the release leaves a click"); +} + +/// A Rotate View drag pressed and released in one frame turns the view to the release, snapped +/// to 15° when Shift is held at the release, though it was not held at the press nor at the end +/// of the frame. +#[test] +fn a_rotate_view_drag_within_one_frame_turns_with_the_release_modifiers() { + let turn = |shift_at_release: bool| { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.session.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + app.select_tool("rotateView"); + let ctx = egui::Context::default(); + frame(&mut app, &ctx, vec![]); + let c = app.canvas_rect.unwrap().center(); + let (from, to) = (c + vec2(100.0, 0.0), c + vec2(100.0, 36.4)); + let up = if shift_at_release { egui::Modifiers::SHIFT } else { egui::Modifiers::NONE }; + let b = |pos, pressed, modifiers| egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers }; + frame(&mut app, &ctx, vec![egui::Event::PointerMoved(from)]); + frame( + &mut app, + &ctx, + vec![ + b(from, true, egui::Modifiers::NONE), + egui::Event::PointerMoved(to), + egui::Event::ModifiersChanged(up), + b(to, false, up), + egui::Event::ModifiersChanged(egui::Modifiers::NONE), + ], + ); + frame(&mut app, &ctx, vec![]); + app.view().unwrap().rotation + }; + let free = turn(false); + assert!(free.rem_euclid(15.0) > 1.0 && free.rem_euclid(15.0) < 14.0, "without Shift the turn is not snapped: {free}"); + let snapped = turn(true); + assert!((snapped.rem_euclid(15.0) % 15.0).abs() < 1e-9, "Shift held at the release snaps the turn: {snapped}"); +} + +/// A Pencil stroke pressed and released in one frame takes the moves between its press and its +/// release, not the moves before the press: it bends through the point it passed, and it starts +/// at the press. +#[test] +fn a_stroke_within_one_frame_takes_the_moves_after_its_press() { + use egui::{Event, Modifiers}; + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.session.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + app.ui.view.smart_guides = false; + app.ui.view.snap_to_point = false; + let ctx = egui::Context::default(); + frame(&mut app, &ctx, vec![]); + let xf = Xf::new(app.canvas_rect.unwrap(), app.view().unwrap()); + let button = |pos, pressed| Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers: Modifiers::NONE }; + let a = app.canvas_rect.unwrap().center() - vec2(100.0, 0.0); + let end = a + vec2(120.0, 0.0); + app.select_tool("pencil"); + frame(&mut app, &ctx, vec![Event::PointerMoved(a - vec2(60.0, 0.0))]); + let mut events = vec![Event::PointerMoved(a - vec2(30.0, 0.0)), Event::PointerMoved(a), button(a, true)]; + events.extend([20.0, 40.0, 60.0, 80.0, 100.0].map(|x: f32| Event::PointerMoved(a + vec2(x, 40.0 - (x - 60.0).abs() * 0.5)))); + events.extend([Event::PointerMoved(end), button(end, false)]); + frame(&mut app, &ctx, events); + frame(&mut app, &ctx, vec![]); + let st = app.session.active().unwrap(); + let r = st.doc.node(*st.selection.objects.first().expect("the stroke is drawn and selected")).unwrap().geometric_bounds().unwrap(); + let (left, right) = (xf.to_doc(a), xf.to_doc(end)); + assert!((r.x0 - left.x).abs() < 1.0 && (r.x1 - right.x).abs() < 1.0, "the stroke runs from the press to the release: {r:?}"); + assert!(r.height() > 10.0, "the stroke bends through the moves after the press: {r:?}"); +} + /// A press on an artboard's name starts no drag. Moving with the button still held is not hover, /// so Shift over a gridline intersection does not position the Perspective Selection tool's plane /// until the button is up. @@ -12280,7 +12494,8 @@ fn only_the_freehand_tools_get_every_move_of_a_frame() { { app.select_tool(tool); let mut moves = vec![]; - let mut out = ctx.run_ui(egui::RawInput { events: events.clone(), ..Default::default() }, |ui| moves = tool_frame_moves(ui, &app, false).0); + let mut out = + ctx.run_ui(egui::RawInput { events: events.clone(), ..Default::default() }, |ui| moves = tool_frame_moves(ui, &app, false, false).0); out.textures_delta.clear(); assert_eq!(moves.len(), if every { 19 } else { 0 }, "{tool}"); } From fabec2187fa310bac44f1f40de0d896fad0fac77 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 22 Nov 2026 13:09:47 -0800 Subject: [PATCH 066/151] History: an Effect Options step names an effect only when every target has it effect.setParams named its step after the edited effect when the targets that have an effect at the index all shared one, so with Feather on one object and no effect on the other the step still recorded Feather. The step now records the effect only when every target has one at the index and all are the same. The target that has the effect is still edited. The i18n menu-label test helper now reads an Effect menu item's label through menus::effect_item_label, the function the menus draw it with. --- crates/engine/src/cmd/effectcmd.rs | 5 +++-- crates/engine/src/tests/history_mem.rs | 28 +++++++++++++++++++++++++- crates/ui-egui/src/i18n/tests.rs | 21 +++++++++---------- crates/ui-egui/src/menus.rs | 2 ++ crates/ui-egui/src/menus/entries.rs | 2 +- crates/ui-egui/src/menus/labels.rs | 6 +++--- 6 files changed, 45 insertions(+), 19 deletions(-) diff --git a/crates/engine/src/cmd/effectcmd.rs b/crates/engine/src/cmd/effectcmd.rs index 2fd764fe8f..6bde9110ee 100644 --- a/crates/engine/src/cmd/effectcmd.rs +++ b/crates/engine/src/cmd/effectcmd.rs @@ -891,8 +891,9 @@ pub(crate) fn set_params(s: &mut Session, p: &Value) -> Result { } } } - // The effect edited, when every target has the same one: a dialog's preview names its step after it. - let one = edited.first().filter(|e| edited.iter().all(|other| other == *e)).cloned().unwrap_or_default(); + // The effect edited, when every target has one at `index` and all are the same: a dialog's + // preview names its step after it. + let one = edited.first().filter(|e| edited.len() == targets.len() && edited.iter().all(|other| other == *e)).cloned().unwrap_or_default(); let ids = s.edit_effect(&one, |s| { edit_effects(s, p, item, C, "Effect Options", &format!("{C}: no effect at index {index}"), index, |fx, index| { let Some(e) = fx.get_mut(index) else { return false }; diff --git a/crates/engine/src/tests/history_mem.rs b/crates/engine/src/tests/history_mem.rs index b26f970966..56580097f2 100644 --- a/crates/engine/src/tests/history_mem.rs +++ b/crates/engine/src/tests/history_mem.rs @@ -2,7 +2,7 @@ //! shared between steps, and past a memory budget the oldest steps go (never the last few). use serde_json::json; -use vectorcraft_doc::{Appearance, Node}; +use vectorcraft_doc::{Appearance, Node, NodeId}; use vectorcraft_geom::shapes; use crate::*; @@ -501,3 +501,29 @@ fn only_steps_an_effect_records_keep_the_effect() { s.commit_interaction().unwrap(); assert_eq!(last(&s), Some(("Feather".into(), None)), "a batch the preview ran"); } + +/// An `effect.setParams` step keeps the effect it edited only when every target has that effect at +/// the index: with one target lacking it, the step keeps none, and the target that has it is still +/// edited. +#[test] +fn effect_options_keep_the_effect_only_when_every_target_has_it() { + let mut s = session_with_rects(2); + let ids: Vec = s.doc().unwrap().doc.layers[0].children().unwrap().iter().map(|n| n.id.0).collect(); + s.execute("effect.apply", &json!({"effect": "stylize.feather", "ids": [ids[0]], "item": null})).unwrap(); + let last = |s: &Session| s.doc().unwrap().history.undo.last().map(|e| (e.label.clone(), e.effect())); + let radius = |s: &Session| { + let d = &s.doc().unwrap().doc; + d.node(NodeId(ids[0])).unwrap().appearance.effects[0].params["radius"].as_f64() + }; + s.begin_interaction("Feather").unwrap(); + s.preview("effect.setParams", &json!({"ids": ids, "item": null, "index": 0, "params": {"radius": 7}})).unwrap(); + s.commit_interaction().unwrap(); + assert_eq!(last(&s), Some(("Feather".into(), None)), "one target without the effect"); + assert_eq!(radius(&s), Some(7.0), "the target with the effect is edited"); + s.execute("effect.apply", &json!({"effect": "stylize.feather", "ids": [ids[1]], "item": null})).unwrap(); + s.begin_interaction("Feather").unwrap(); + s.preview("effect.setParams", &json!({"ids": ids, "item": null, "index": 0, "params": {"radius": 9}})).unwrap(); + s.commit_interaction().unwrap(); + assert_eq!(last(&s), Some(("Feather".into(), Some("stylize.feather"))), "every target with the effect"); + assert_eq!(radius(&s), Some(9.0)); +} diff --git a/crates/ui-egui/src/i18n/tests.rs b/crates/ui-egui/src/i18n/tests.rs index 8c0e0587dc..5aa474704f 100644 --- a/crates/ui-egui/src/i18n/tests.rs +++ b/crates/ui-egui/src/i18n/tests.rs @@ -2287,17 +2287,14 @@ fn menu_item_effect<'a>(id: &str, p: &'a serde_json::Value) -> Option<&'a str> { p.get("effect").and_then(serde_json::Value::as_str).filter(|_| matches!(id, "effect.apply" | "effect.dialog")) } -/// The label a menu item shows in `lang`, as the menus resolve it: an Effect menu item by its -/// effect's `@id` row when the catalog has one, any other command by its id's row or its English -/// label, and a submenu or an unbuilt item by its English label. -fn shown_menu_label(lang: Lang, item: &crate::menus::Item) -> Option<&'static str> { +/// The label a menu item shows in `lang`, as the menus resolve it: a built-in Effect menu item by +/// its effect's name ([`crate::menus::effect_item_label`]), any other command by its id's row or +/// its English label, and a submenu or an unbuilt item by its English label. +fn shown_menu_label(lang: Lang, item: &crate::menus::Item) -> Option { use crate::menus::Item; match item { - Item::Cmd(l, id, p) => { - let by_effect = menu_item_effect(id, p).map(|e| tr_id(lang, e, "")).filter(|s| !s.is_empty()); - Some(by_effect.unwrap_or_else(|| tr_id(lang, id, l))) - } - Item::Todo(l, _) | Item::Sub(l, _) => Some(tr(lang, l)), + Item::Cmd(l, id, p) => Some(crate::menus::effect_item_label(id, p, lang).unwrap_or_else(|| tr_id(lang, id, l).to_string())), + Item::Todo(l, _) | Item::Sub(l, _) => Some(tr(lang, l).to_string()), Item::Header(_) | Item::Sep => None, } } @@ -2309,7 +2306,7 @@ fn shown_menu_label(lang: Lang, item: &crate::menus::Item) -> Option<&'static st fn menu_items_side_by_side_have_different_labels() { use crate::menus::Item; fn walk(lang: Lang, path: &str, items: &[Item], out: &mut Vec) { - let mut seen: std::collections::BTreeMap<&str, (&str, &str)> = std::collections::BTreeMap::new(); + let mut seen: std::collections::BTreeMap = std::collections::BTreeMap::new(); for item in items { let Some(shown) = shown_menu_label(lang, item) else { continue }; let (english, what) = match item { @@ -2317,7 +2314,7 @@ fn menu_items_side_by_side_have_different_labels() { Item::Todo(l, _) | Item::Sub(l, _) => (*l, "submenu or unbuilt item"), Item::Header(_) | Item::Sep => continue, }; - match seen.get(shown) { + match seen.get(&shown) { Some(&(other, other_what)) if other != english => { out.push(format!("{}: {path}: {other:?} ({other_what}) and {english:?} ({what}) both show {shown:?}", lang.0.code)); } @@ -2369,7 +2366,7 @@ fn menu_items_never_show_an_id() { if let crate::menus::Item::Cmd(l, id, p) = item { let key = menu_item_effect(id, p).unwrap_or(id); let shown = shown_menu_label(lang, item).unwrap_or_default(); - if label_shows_an_id(shown, key) && !label_shows_an_id(l, key) { + if label_shows_an_id(&shown, key) && !label_shows_an_id(l, key) { out.push(format!("{}: {l:?} ({key}) shows {shown:?}", lang.0.code)); } } diff --git a/crates/ui-egui/src/menus.rs b/crates/ui-egui/src/menus.rs index ac5ec6825b..13fa7c5a0c 100644 --- a/crates/ui-egui/src/menus.rs +++ b/crates/ui-egui/src/menus.rs @@ -76,6 +76,8 @@ pub use invoke::{click_target, invoke, invoke_from_system_menu}; pub(crate) use keyboard::handle_input as handle_keyboard_input; // Shared numeric fields preserve their caret when a transient menu returns their focus. pub(crate) use keyboard::restoring_field_focus; +#[cfg(test)] +pub(crate) use labels::effect_item_label; pub(crate) use labels::lists_plugin; pub(crate) use labels::shows_a_name; pub use labels::{CONTEXT_LABELS, DYNAMIC_LABELS, display_label, dynamic_label, item_shortcut, menu_strings}; diff --git a/crates/ui-egui/src/menus/entries.rs b/crates/ui-egui/src/menus/entries.rs index 5a3ade8633..5a763271cd 100644 --- a/crates/ui-egui/src/menus/entries.rs +++ b/crates/ui-egui/src/menus/entries.rs @@ -66,7 +66,7 @@ pub fn entry<'a>(app: &VectorcraftApp, it: &'a Item) -> Option> { /// draw it in the UI language: an effect's own name (Pathfinder › Add), an object's name, a /// spelling suggestion, or [`display_label`]. pub fn shown_label(app: &VectorcraftApp, id: &str, p: &Value, label: &str) -> String { - effect_item_label(id, p) + effect_item_label(id, p, crate::i18n::current()) .or_else(|| unlock_item_label(app, id, p, crate::i18n::current())) .or_else(|| spelling_item_label(id, p)) .unwrap_or_else(|| display_label(app, id, label)) diff --git a/crates/ui-egui/src/menus/labels.rs b/crates/ui-egui/src/menus/labels.rs index dd73c842f7..04da5269b0 100644 --- a/crates/ui-egui/src/menus/labels.rs +++ b/crates/ui-egui/src/menus/labels.rs @@ -199,11 +199,11 @@ pub fn display_label(app: &VectorcraftApp, id: &str, label: &str) -> String { } } -/// The label of an Effect menu item in the UI language, by the effect's own id +/// The label of an Effect menu item in `lang`, by the effect's own id /// ([`crate::i18n::effect_menu_label`]). Every effect item runs `effect.apply` or `effect.dialog`, /// so the command id can't tell them apart. `None` for any other item, and for a plug-in effect, /// whose item shows the plug-in's own text. -pub(super) fn effect_item_label(id: &str, p: &Value) -> Option { +pub(crate) fn effect_item_label(id: &str, p: &Value, lang: crate::i18n::Lang) -> Option { if !matches!(id, "effect.apply" | "effect.dialog") { return None; } @@ -211,7 +211,7 @@ pub(super) fn effect_item_label(id: &str, p: &Value) -> Option { if vectorcraft_plugins::effect::plugin_id(effect).is_some() { return None; } - crate::i18n::effect_menu_label(crate::i18n::current(), effect) + crate::i18n::effect_menu_label(lang, effect) } /// The label of an item of the canvas context menu's Unlock submenu (`layer.setProps` with one id From 744faaab6c64b75cd4e0c7062b33dbf970ada272 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 22 Nov 2026 13:20:56 -0800 Subject: [PATCH 067/151] Tests: startup script tests remove their temporary folders `tmp_dir` in `crates/engine/tests/script_startup.rs` now returns `vectorcraft_testkit::TempDir`, which deletes the folder when the test ends, also after a failed assertion. Before, every run left its folders under the system temporary directory. --- crates/engine/tests/script_startup.rs | 12 +++++------- 1 file changed, 5 insertions(+), 7 deletions(-) diff --git a/crates/engine/tests/script_startup.rs b/crates/engine/tests/script_startup.rs index fca883cfc0..4bd370d9b6 100644 --- a/crates/engine/tests/script_startup.rs +++ b/crates/engine/tests/script_startup.rs @@ -13,6 +13,7 @@ use std::sync::Mutex; use serde_json::{Value, json}; use vectorcraft_engine::Session; use vectorcraft_plugins::safe_mode; +use vectorcraft_testkit::TempDir; static LOCK: Mutex<()> = Mutex::new(()); @@ -42,12 +43,9 @@ impl Drop for Fresh { } } -/// A new, empty folder for test `tag`. -fn tmp_dir(tag: &str) -> PathBuf { - let d = std::env::temp_dir().join(format!("vc-script-startup-{tag}-{}", std::process::id())); - let _ = std::fs::remove_dir_all(&d); - std::fs::create_dir_all(&d).unwrap(); - d +/// A new, empty folder for test `tag`, removed with everything in it when the test ends. +fn tmp_dir(tag: &str) -> TempDir { + TempDir::new(&format!("script-startup-{tag}")) } /// Writes `text` to `name` under `dir`, folders included. @@ -89,7 +87,7 @@ fn startup_scripts_are_off_by_default_and_run_nothing() { write(&dir, "a.jsx", "vc.log('ran');"); let mut s = Session::new(); assert!(!s.prefs.run_startup_scripts, "off by default"); - s.attach_startup_scripts_dir(dir.clone()); + s.attach_startup_scripts_dir(dir.to_path_buf()); assert_eq!(s.startup_skip(), Some("off")); let r = s.execute("script.startup.run", &json!({"reason": "launch"})).unwrap(); assert_eq!(r, json!({"reason": "launch", "skipped": true, "why": "off"})); From b16377d22358e0bef3c994767a38f5a5463430f7 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 22 Nov 2026 14:24:15 -0800 Subject: [PATCH 068/151] Canvas: a press in one frame ends at its own release, and a one-frame Animated Zoom drag scrubs When a frame holds the release of an earlier press, then a new press and its release, the new press now ends at the release after it: its Up, the pan or turn of the view, the modifiers, Space and Backtick all come from that release, and a stroke's moves stop there. Before, they came from the first release in the frame, which belongs to the earlier press. With Animated Zoom on, a Zoom tool press that moves more than the scrub slop and goes up in the same frame now zooms with the pointer about the press, as it does over several frames, instead of stepping as a click. Only the moves before the button-up count; a press that stays within the slop still steps. --- crates/ui-egui/src/canvas/drag.rs | 58 ++++++++------------- crates/ui-egui/src/canvas/input.rs | 79 ++++++++++++++++------------ crates/ui-egui/src/canvas/tests.rs | 82 ++++++++++++++++++++++++++++++ 3 files changed, 151 insertions(+), 68 deletions(-) diff --git a/crates/ui-egui/src/canvas/drag.rs b/crates/ui-egui/src/canvas/drag.rs index 9aadc14f3d..4064b68c39 100644 --- a/crates/ui-egui/src/canvas/drag.rs +++ b/crates/ui-egui/src/canvas/drag.rs @@ -121,31 +121,13 @@ pub(super) fn space_seen(ui: &Ui) -> Option { }) } -/// Whether Backtick was held when `button` went up in this frame, with `before` its state at the end -/// of the frame before ([`backquote_seen`]). Its state as the frame began is the opposite of its -/// first press or release in the frame; when the window lost the focus first (which lets go of every -/// key without a release), it is `before`; with neither, it is its state now. The frame's presses, -/// releases and focus losses before the button-up then apply in the order they came. Without a -/// button-up in this frame, its state now. -pub(super) fn backquote_at_release(ui: &Ui, button: egui::PointerButton, before: Option) -> bool { - key_at_release(ui, egui::Key::Backtick, button, before) -} - -/// Whether `key` was held when `button` went up in this frame, by the rules of -/// [`backquote_at_release`], with `before` its state at the end of the frame before. -pub(super) fn key_at_release(ui: &Ui, key: egui::Key, button: egui::PointerButton, before: Option) -> bool { - key_at_button(ui, key, button, false, before) -} - -/// Whether `key` was held when `button` went down in this frame, by the rules of -/// [`backquote_at_release`] with the button-down in place of the button-up. -pub(super) fn key_at_press(ui: &Ui, key: egui::Key, button: egui::PointerButton, before: Option) -> bool { - key_at_button(ui, key, button, true, before) -} - -/// Whether `key` was held when `button` first went down (`pressed`) or up in this frame -/// ([`key_at_release`], [`key_at_press`]). -fn key_at_button(ui: &Ui, key: egui::Key, button: egui::PointerButton, pressed: bool, before: Option) -> bool { +/// Whether `key` (Backtick, Space) was held at the frame's event at index `at`, a button going down +/// or up, with `before` its state at the end of the frame before ([`backquote_seen`], [`space_seen`]). +/// Its state as the frame began is the opposite of its first press or release in the frame; when +/// the window lost the focus first (which lets go of every key without a release), it is `before`; +/// with neither, it is its state now. The frame's presses, releases and focus losses before `at` +/// then apply in the order they came. Without `at`, its state now. +pub(super) fn key_at_event(ui: &Ui, key: egui::Key, at: Option, before: Option) -> bool { ui.input(|i| { let now = i.key_down(key); // A press or release of `key` (`Some(pressed)`), or a focus loss (`None`). @@ -154,9 +136,7 @@ fn key_at_button(ui: &Ui, key: egui::Key, button: egui::PointerButton, pressed: egui::Event::WindowFocused(false) => Some(None), _ => None, }; - let Some(up) = - i.events.iter().position(|e| matches!(e, egui::Event::PointerButton { button: b, pressed: p, .. } if *b == button && *p == pressed)) - else { + let Some(up) = at.map(|k| k.min(i.events.len())) else { return now; }; let start = match i.events.iter().find_map(step) { @@ -168,6 +148,13 @@ fn key_at_button(ui: &Ui, key: egui::Key, button: egui::PointerButton, pressed: }) } +/// Whether `key` was held when `button` first went down in this frame, by the rules of +/// [`key_at_event`]. +pub(super) fn key_at_press(ui: &Ui, key: egui::Key, button: egui::PointerButton, before: Option) -> bool { + let at = ui.input(|i| i.events.iter().position(|e| matches!(e, egui::Event::PointerButton { button: b, pressed: true, .. } if *b == button))); + key_at_event(ui, key, at, before) +} + /// The pen pressure (0..1) of the press in progress: the force of this frame's pen or touch /// input, else the pressure in the host's feed while a pen is the pointer that moved last /// ([`crate::Services::stylus`]: [`StylusFeed::press`] for a new press, [`StylusFeed::held`] @@ -238,7 +225,8 @@ pub(super) fn frame_moves(ui: &Ui, stylus: Option<&StylusFeed>, release: Option< } /// [`frame_moves`], and with `since_press` only the moves after the primary button first went down -/// in this frame: a press that began in this frame did not pass the positions before it. +/// in this frame: a press that began in this frame did not pass the positions before it. The moves +/// then stop at the first button-up after that press, not at a release that came before it. pub(super) fn frame_moves_since( ui: &Ui, stylus: Option<&StylusFeed>, @@ -248,17 +236,15 @@ pub(super) fn frame_moves_since( let samples = stylus.map(StylusFeed::take_moves).unwrap_or_default(); ui.input(|i| { // How many of the frame's moves came before the press, when only those after it count. - let before_press = if since_press { - i.events - .iter() - .position(|e| matches!(e, egui::Event::PointerButton { button: egui::PointerButton::Primary, pressed: true, .. })) - .map_or(0, |k| i.events.iter().take(k).filter(|e| matches!(e, egui::Event::PointerMoved(_))).count()) + let press = if since_press { + i.events.iter().position(|e| matches!(e, egui::Event::PointerButton { button: egui::PointerButton::Primary, pressed: true, .. })) } else { - 0 + None }; + let before_press = press.map_or(0, |k| i.events.iter().take(k).filter(|e| matches!(e, egui::Event::PointerMoved(_))).count()); // How many of the frame's moves came before the button-up, and where it came, if it came. let before_up = release.and_then(|b| { - i.events.iter().enumerate().find_map(|(k, e)| match e { + i.events.iter().enumerate().skip(press.map_or(0, |k| k + 1)).find_map(|(k, e)| match e { egui::Event::PointerButton { pos, button, pressed: false, .. } if *button == b => { Some((i.events.iter().take(k).filter(|e| matches!(e, egui::Event::PointerMoved(_))).count(), *pos)) } diff --git a/crates/ui-egui/src/canvas/input.rs b/crates/ui-egui/src/canvas/input.rs index 20550efe25..785f1225ac 100644 --- a/crates/ui-egui/src/canvas/input.rs +++ b/crates/ui-egui/src/canvas/input.rs @@ -1,8 +1,8 @@ use super::artboards::{artboard_name_at, begin_artboard_name_edit, name_press_id, select_named_artboard}; use super::drag::{ - FrameMove, HoverContext, apply_requests, backquote_at_release, backquote_seen, dispatch, drag_art_out, drag_id, drag_layer_id, drag_pos_id, - drop_press, key_at_press, key_at_release, mods, move_pose, on_canvas, pen_pose, pen_pressure, space_lends_view_tools, space_seen, - tool_drag_doc_id, tool_drag_mods_changed, tool_drag_moved, tool_frame_moves, tool_holds, tool_press_doc_id, + FrameMove, HoverContext, apply_requests, backquote_seen, dispatch, drag_art_out, drag_id, drag_layer_id, drag_pos_id, drop_press, key_at_event, + key_at_press, mods, move_pose, on_canvas, pen_pose, pen_pressure, space_lends_view_tools, space_seen, tool_drag_doc_id, tool_drag_mods_changed, + tool_drag_moved, tool_frame_moves, tool_holds, tool_press_doc_id, }; use super::view::{ HOLD_DELAY, HOLD_ZOOM, SCRUB_SLOP, SCRUB_ZOOM, WheelTurn, animated_zoom, edge_scroll, edge_scroll_pixels, pan_pixels, pan_ppp, rotate_about, @@ -136,13 +136,33 @@ pub(super) fn handle_input(app: &mut VectorcraftApp, ui: &Ui, resp: &egui::Respo (Pointing { ..f }, backquote_now) }; begin_drag(app, ui, &press, start, backquote); - if released && let Some(d) = ui.data(|dd| dd.get_temp::(drag_id())) { - // A pan or a turn of the view follows the pointer to where the button went up, with - // the modifiers held then (Shift snaps the turn). - if matches!(d, Drag::Pan { .. } | Drag::RotateView { .. }) - && let Some(up) = release_pos(ui, primary, false) - { - drag_held(app, ui, &Pointing { m: release_mods(ui, primary).unwrap_or(m), ..press }, d, up); + if released && let Some(mut d) = ui.data(|dd| dd.get_temp::(drag_id())) { + let span = press_span(ui, primary); + if let Some((_, up, up_mods)) = ending_release(ui, primary, span.as_ref()) { + match d { + // A pan or a turn of the view follows the pointer to where the button went + // up, with the modifiers held then (Shift snaps the turn). + Drag::Pan { .. } | Drag::RotateView { .. } => drag_held(app, ui, &Pointing { m: up_mods, ..press }, d, up), + // An Animated Zoom press that moved more than the scrub's slop before it went + // up zooms with the pointer as a held one does, about where it was pressed; + // one that stayed within it is a click. Only the moves before the button-up count. + Drag::ZoomScrub { start: from, held, .. } => { + let moved = ui.input(|i| { + let span = i.events.get(span.clone().unwrap_or_default()).unwrap_or_default(); + std::iter::once(up) + .chain(span.iter().filter_map(|e| if let egui::Event::PointerMoved(q) = e { Some(*q) } else { None })) + .any(|q| (q - from).length() > SCRUB_SLOP) + }); + if moved { + let ui_zoom = app.canvas_ui_zoom; + if let Some(vm) = app.view_mut() { + zoom_about(vm, rect, from, vm.zoom * (f64::from(up.x - from.x) * SCRUB_ZOOM).exp(), ui_zoom); + } + d = Drag::ZoomScrub { start: from, held, moved: true }; + } + } + _ => {} + } } end_drag(app, ui, &f, d, egui::PointerButton::Primary, start, true); } @@ -618,13 +638,15 @@ fn dispatch_frame_moves(app: &mut VectorcraftApp, ui: &Ui, f: &Pointing, backquo /// A gesture whose `button` went up ends where it went up, with the modifiers and Space held then: /// the moves and key changes after the release in this frame do not count. Without a release in /// this frame, it ends at `p` with the modifiers and Space held now. `pressed_here` says that the -/// gesture was pressed in this frame too ([`drag_released`]). +/// gesture was pressed in this frame too ([`drag_released`]), and then the release that ends it is +/// the one after that press ([`ending_release`]). fn end_drag(app: &mut VectorcraftApp, ui: &Ui, f: &Pointing, d: Drag, button: egui::PointerButton, p: Pos2, pressed_here: bool) { - let m = release_mods(ui, button).unwrap_or(f.m); - let space = space_lends_view_tools(app, m, key_at_release(ui, egui::Key::Space, button, f.space_before)); - let up = Pointing { m, space, ..*f }; let cut = if pressed_here { press_span(ui, button) } else { None }; - drag_released(app, ui, &up, d, release_pos(ui, button, false).unwrap_or(p), cut); + let release = ending_release(ui, button, cut.as_ref()); + let m = release.map_or(f.m, |(_, _, m)| m); + let space = space_lends_view_tools(app, m, key_at_event(ui, egui::Key::Space, release.map(|(k, ..)| k), f.space_before)); + let up = Pointing { m, space, ..*f }; + drag_released(app, ui, &up, d, release.map_or(p, |(_, q, _)| q), cut); } /// A gesture released at `p`: the view settles, or the tool gets its up. With `cut`, the gesture @@ -638,7 +660,8 @@ fn drag_released(app: &mut VectorcraftApp, ui: &Ui, f: &Pointing, d: Drag, p: Po // Where the pointer was in the frame before: a zoom marquee moved with Space follows it. let before: Option = ui.data(|dd| dd.get_temp(drag_pos_id())); // Backtick as it was at the button-up: a key pressed or released later in the frame does not count. - let backquote = backquote_at_release(ui, egui::PointerButton::Primary, f.backquote_before); + let release = ending_release(ui, egui::PointerButton::Primary, cut.as_ref()).map(|(k, ..)| k); + let backquote = key_at_event(ui, egui::Key::Backtick, release, f.backquote_before); // Whether Shift, Alt, Cmd/Ctrl, Space or Backtick changed since the drag's last frame, read // before the drag's state is cleared below. let mods_changed = matches!(d, Drag::Tool) && tool_drag_mods_changed(ui, mods(m, space), backquote); @@ -805,14 +828,16 @@ fn triple_click(app: &mut VectorcraftApp, ui: &Ui, f: &Pointing, p: Pos2) { dispatch(app, &ev, view); } -/// Where `button` went up: the first release ends a drag, the last classifies this frame's click. -fn release_pos(ui: &Ui, button: egui::PointerButton, last: bool) -> Option { +/// The release of `button` that ends a gesture, with its index among the frame's events, where it +/// came and the modifiers held then. With `cut`, the gesture was pressed in this frame, and its +/// release is the one that ends `cut` ([`press_span`]), not one that came before the press; else +/// it is the first release in this frame. `None` without one. +fn ending_release(ui: &Ui, button: egui::PointerButton, cut: Option<&std::ops::Range>) -> Option<(usize, Pos2, egui::Modifiers)> { ui.input(|i| { - let mut releases = i.events.iter().filter_map(|e| match e { - egui::Event::PointerButton { pos, button: b, pressed: false, .. } if *b == button => Some(*pos), + i.events.iter().enumerate().skip(cut.map_or(0, |r| r.end)).find_map(|(k, e)| match e { + egui::Event::PointerButton { pos, button: b, pressed: false, modifiers } if *b == button => Some((k, *pos, *modifiers)), _ => None, - }); - if last { releases.next_back() } else { releases.next() } + }) }) } @@ -847,16 +872,6 @@ fn press_span(ui: &Ui, button: egui::PointerButton) -> Option Option { - ui.input(|i| { - i.events.iter().find_map(|e| match e { - egui::Event::PointerButton { button: b, pressed: false, modifiers, .. } if *b == button => Some(*modifiers), - _ => None, - }) - }) -} - /// Whether Space moves the Zoom tool's marquee in the drag under way ([`zoom_marquee_start`]). fn zoom_space_free_id() -> egui::Id { egui::Id::unique("canvas-zoom-space-free") diff --git a/crates/ui-egui/src/canvas/tests.rs b/crates/ui-egui/src/canvas/tests.rs index 9646093f6f..42ba46dfc6 100644 --- a/crates/ui-egui/src/canvas/tests.rs +++ b/crates/ui-egui/src/canvas/tests.rs @@ -1547,6 +1547,88 @@ fn a_zoom_click_within_one_frame_starts_where_it_was_pressed() { } } +/// With Animated Zoom on, a Zoom tool press dragged sideways and released in one frame zooms with +/// the pointer about the press, as it does over several frames, instead of stepping as a click. A +/// press released where it went down, with a move after the release in that frame, still steps. +#[test] +fn an_animated_zoom_drag_within_one_frame_scrubs() { + use egui::Event; + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.session.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + app.select_tool("zoom"); + let ctx = egui::Context::default(); + frame(&mut app, &ctx, vec![]); + let rect = app.canvas_rect.unwrap(); + let at = rect.center() - vec2(100.0, 50.0); + let to = at + vec2(100.0, 0.0); + let button = |pos, pressed| Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() }; + let doc_at = |app: &VectorcraftApp, p: Pos2| Xf::new(rect, app.view().unwrap()).to_doc(p); + frame(&mut app, &ctx, vec![Event::PointerMoved(at)]); + let (z0, pinned) = (app.view().unwrap().zoom, doc_at(&app, at)); + frame(&mut app, &ctx, vec![button(at, true), Event::PointerMoved(to), button(to, false)]); + frame(&mut app, &ctx, vec![]); + let z1 = app.view().unwrap().zoom; + assert!((z1 / z0 - 2.0).abs() < 1e-6, "100 points right doubles the zoom: {z0} → {z1}"); + assert!(doc_at(&app, at).distance(pinned) < 1e-6, "about the press"); + app.view_mut().unwrap().zoom = z0; + frame(&mut app, &ctx, vec![Event::PointerMoved(at)]); + frame(&mut app, &ctx, vec![button(at, true), button(at, false), Event::PointerMoved(to)]); + frame(&mut app, &ctx, vec![]); + assert_eq!(app.view().unwrap().zoom, crate::state::next_zoom(z0, true), "a click steps the zoom"); +} + +/// A press and release in one frame that follow the release of an earlier press in that frame end +/// at their own release, with its modifiers: with Animated Zoom off, a Zoom tool click steps the +/// zoom in though Alt was held at the earlier release, and a drag zooms to the area it dragged +/// across, not to the earlier release. +#[test] +fn a_press_within_one_frame_after_an_earlier_release_ends_at_its_own_release() { + use egui::Event; + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.session.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + app.run("prefs.set", json!({"key": "animatedZoom", "value": false})).unwrap(); + app.select_tool("zoom"); + let ctx = egui::Context::default(); + frame(&mut app, &ctx, vec![]); + let rect = app.canvas_rect.unwrap(); + let at = rect.center() - vec2(100.0, 50.0); + let to = at + vec2(100.0, 50.0); + let (near, far) = (rect.center() + vec2(110.0, 90.0), rect.center() + vec2(150.0, 120.0)); + let button = |pos, pressed, modifiers| Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers }; + let none = egui::Modifiers::NONE; + let z0 = app.view().unwrap().zoom; + // A press dragged in earlier frames, then in one frame its release, a new press and that + // press's release. + let run = |app: &mut VectorcraftApp, events: Vec| { + app.view_mut().unwrap().zoom = z0; + frame(app, &ctx, vec![Event::PointerMoved(near)]); + frame(app, &ctx, vec![button(near, true, none)]); + frame(app, &ctx, vec![Event::PointerMoved(far)]); + frame(app, &ctx, events); + frame(app, &ctx, vec![Event::ModifiersChanged(none)]); + app.view().unwrap().zoom + }; + let alt = egui::Modifiers::ALT; + let z = run( + &mut app, + vec![ + Event::ModifiersChanged(alt), + button(far, false, alt), + Event::ModifiersChanged(none), + Event::PointerMoved(at), + button(at, true, none), + button(at, false, none), + ], + ); + assert_eq!(z, crate::state::next_zoom(z0, true), "the click zooms in with the modifiers of its own release"); + let z = run( + &mut app, + vec![button(far, false, none), Event::PointerMoved(at), button(at, true, none), Event::PointerMoved(to), button(to, false, none)], + ); + let area = z0 * f64::from((rect.width() / 100.0).min(rect.height() / 50.0)); + assert!((z - area).abs() < 1e-6, "the drag zooms to its own area: {z0} → {z}, not {area}"); +} + /// Space pressed after a tool drag's release, in the same frame, does not count for the drag: the /// Rectangle tool's last move still resizes the rectangle instead of moving it. #[test] From d2600b0bd9d4afca7cc04fa0eb13eeefe2947d42 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 22 Nov 2026 15:39:40 -0800 Subject: [PATCH 069/151] Plug-ins: a JavaScript manifest opened by path is installed without reading it first Opening a JavaScript plug-in's .vcplugin by its path now goes straight to plugin.install {path}, which reads the manifest and its script with the plug-in loader's limits. The app's file reader no longer reads the whole file before the plug-in branch. The plugin.install params text is reworded so that every alternative starts with its parameter name. --- crates/engine/src/cmd/plugin.rs | 2 +- crates/ui-egui/src/io/open.rs | 6 ++++++ crates/ui-egui/src/tests/plugins.rs | 21 +++++++++++++++++++++ 3 files changed, 28 insertions(+), 1 deletion(-) diff --git a/crates/engine/src/cmd/plugin.rs b/crates/engine/src/cmd/plugin.rs index 6b7ce246d2..a048ac45de 100644 --- a/crates/engine/src/cmd/plugin.rs +++ b/crates/engine/src/cmd/plugin.rs @@ -1317,7 +1317,7 @@ pub fn specs() -> Vec { "Install Plug-in", [], None, - "{path: a .wasm file, or a JavaScript plug-in's .vcplugin manifest, read with the .js file its script names (desktop) | dataBase64: the module, or a JavaScript plug-in as one JSON object, its manifest with the script's text in source (+ name?: shown as its source), replace?: bool (true once the user agreed: a module with other bytes than the plug-in installed with its id, or with none installed, one whose id has settings or a cache in the plug-in store, installs only with it, takes that plug-in's place and gets its settings and cache; false: one whose id is installed is refused; left out, the same module installs again), name?: file name (with dataBase64), allowHeavy?: bool (a filter whose manifest asks for a heavy budget, budget \"heavy\" in plugin.inspect, installs only with it), grant?: [permission] (a plug-in whose manifest lists permissions, needsApproval in plugin.inspect, installs only when grant holds every one of them; the grant is recorded with the module's hash and covers only that module, so a module with other bytes needs a new grant even when it lists the same permissions; installing a module that lists no permissions forgets the grant held for its id; a refused install keeps the grant, a failed write of the module to the plug-in store leaves the grant in the store, and a stored module that is disabled or not read in Safe Mode keeps the grant for its id; with a plug-in store attached, only the grants kept there count; a request's allowHeavy and grant are refused unless the session was started with vectorcraft-cli --allow-plugin-grants: in the desktop app a person approves the install, see ui.installPlugin, and a module whose hash is already recorded, by a person's approval or by a grant accepted under that flag, needs no grant), hash?: string (the module's SHA-256 as plugin.inspect gave it: a module with other bytes is refused)} validate and install a plug-in for this session (with a plug-in store, the install waits while another window or process changes the store and writes the module and its grant before that window or process changes it again; when the store's disabled.lock can't be locked, nothing is installed) (a module whose commandAllowlist names a command no plug-in may call, such as one that reads or writes files, is refused) → its plugin.list entry, plus unknownCommands?: [id] (commandAllowlist ids no command has; a call of one fails)", + "{path: a .wasm file or a JavaScript plug-in's .vcplugin manifest (read with the .js file its script names) (desktop) | dataBase64: the module or a JavaScript plug-in as one JSON object (its manifest, with the script's text in source) (+ name?: shown as its source), replace?: bool (true once the user agreed: a module with other bytes than the plug-in installed with its id, or with none installed, one whose id has settings or a cache in the plug-in store, installs only with it, takes that plug-in's place and gets its settings and cache; false: one whose id is installed is refused; left out, the same module installs again), name?: file name (with dataBase64), allowHeavy?: bool (a filter whose manifest asks for a heavy budget, budget \"heavy\" in plugin.inspect, installs only with it), grant?: [permission] (a plug-in whose manifest lists permissions, needsApproval in plugin.inspect, installs only when grant holds every one of them; the grant is recorded with the module's hash and covers only that module, so a module with other bytes needs a new grant even when it lists the same permissions; installing a module that lists no permissions forgets the grant held for its id; a refused install keeps the grant, a failed write of the module to the plug-in store leaves the grant in the store, and a stored module that is disabled or not read in Safe Mode keeps the grant for its id; with a plug-in store attached, only the grants kept there count; a request's allowHeavy and grant are refused unless the session was started with vectorcraft-cli --allow-plugin-grants: in the desktop app a person approves the install, see ui.installPlugin, and a module whose hash is already recorded, by a person's approval or by a grant accepted under that flag, needs no grant), hash?: string (the module's SHA-256 as plugin.inspect gave it: a module with other bytes is refused)} validate and install a plug-in for this session (with a plug-in store, the install waits while another window or process changes the store and writes the module and its grant before that window or process changes it again; when the store's disabled.lock can't be locked, nothing is installed) (a module whose commandAllowlist names a command no plug-in may call, such as one that reads or writes files, is refused) → its plugin.list entry, plus unknownCommands?: [id] (commandAllowlist ids no command has; a call of one fails)", always, install ), diff --git a/crates/ui-egui/src/io/open.rs b/crates/ui-egui/src/io/open.rs index 70797c4a0a..18d1c7e598 100644 --- a/crates/ui-egui/src/io/open.rs +++ b/crates/ui-egui/src/io/open.rs @@ -575,6 +575,12 @@ fn open_file_with(app: &mut VectorcraftApp, path: &str, background: bool, p: &Va note_recent(app, path); return Ok(Value::Null); } + // A JavaScript plug-in's manifest is read by `plugin.install {path}`, with the script it names. + if opens_as(path) == Some(OpensAs::Plugin) && vectorcraft_plugins::registry::is_js_package(std::path::Path::new(path)) { + install_module(app, json!({ "path": path }))?; + note_recent(app, path); + return Ok(Value::Null); + } // A file only an importer plug-in reads is not read past the importer's input limit. check_import_size(path, false)?; let mut bytes = read(app, path)?; diff --git a/crates/ui-egui/src/tests/plugins.rs b/crates/ui-egui/src/tests/plugins.rs index 13484b098a..e2288b6bbc 100644 --- a/crates/ui-egui/src/tests/plugins.rs +++ b/crates/ui-egui/src/tests/plugins.rs @@ -743,3 +743,24 @@ fn opening_a_javascript_manifest_installs_it_with_its_script() { assert_eq!(vectorcraft_plugins::registry::get(id).and_then(|p| p.script().map(str::to_string)).as_deref(), Some("open.js")); app.run("plugin.remove", json!({"id": id})).unwrap(); } + +/// Opening a JavaScript plug-in's `.vcplugin` by its path installs it through `plugin.install +/// {path}` without the app's file reader reading the manifest first. +#[test] +fn opening_a_javascript_manifest_by_path_does_not_read_it_first() { + let mut app = app(); + app.services.read = Some(Box::new(|_: &str| Err("the whole file was read".to_string()))); + let id = "test.ui.js.open.path"; + let dir = std::env::temp_dir().join(format!("vc-ui-js-open-path-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + let manifest = json!({"id": id, "name": "Open JS by path", "kind": "filter", "runtime": "js", "script": "open.js"}).to_string(); + let path = dir.join("open.vcplugin"); + std::fs::write(&path, &manifest).unwrap(); + std::fs::write(dir.join("open.js"), "function run(input) { return input; }").unwrap(); + let r = io::open_path(&mut app, &path.display().to_string()); + std::fs::remove_dir_all(&dir).unwrap(); + assert_eq!(r, Ok(Value::Null)); + assert_eq!(vectorcraft_plugins::registry::get(id).and_then(|p| p.script().map(str::to_string)).as_deref(), Some("open.js")); + app.run("plugin.remove", json!({"id": id})).unwrap(); +} From 3886c934122f3c01d8839030d29e3d2500a32776 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 22 Nov 2026 17:31:07 -0800 Subject: [PATCH 070/151] Scripts: say that script.grants lists no grants when the lock is busy When the grants file's lock cannot be taken, script.grants returns the error without reading the file, so the grants list is empty. docs/mcp.md, the command's params text and the doc comments of stored_grants and the Script File Access loader now say so, and keep "lists the well-formed grants it can still read" for a file that is unreadable, over 4 MiB, of another version, malformed or over 4096 grants. --- crates/engine/src/cmd/scripts.rs | 2 +- crates/engine/src/script/files.rs | 3 ++- crates/ui-egui/src/prefs_dialog/script_access.rs | 2 +- docs/mcp.md | 8 +++++--- 4 files changed, 9 insertions(+), 6 deletions(-) diff --git a/crates/engine/src/cmd/scripts.rs b/crates/engine/src/cmd/scripts.rs index 44b8b7f432..30cd846e29 100644 --- a/crates/engine/src/cmd/scripts.rs +++ b/crates/engine/src/cmd/scripts.rs @@ -95,7 +95,7 @@ pub fn specs() -> Vec { "List Script File Permissions", [], None, - "{} the file access people allowed scripts with Always in a file dialog, kept in Script Grants.json next to the settings: each for one script file with one text and the files it includes (their SHA-256), so a changed or moved script, or a changed included file, has none, and with the SHA-256 of each source the run that kept it evaluated (files $.evalFile ran, strings given to eval and Function; at most 256), so a run loses it before it evaluates other code, or when its named engine holds code the grant was not kept for; at most 4096 → {grants: [{script: the script file's path, sha256, code: [SHA-256 of each evaluated source, of its UTF-16 code units in little-endian order], path: the file or folder allowed, write: it may be written, folder: the grant is a folder's, with everything in it (a file's grant is its own path only)}], file: the grants file's path | null (a session without a settings folder, and the web), error?: why the grants file cannot be read or changed, when it is there and cannot be read, is over 4 MiB, is not a version 1 grants file, holds a grant that is not well formed or more than 4096 grants, or its lock cannot be taken (grants then lists the well-formed grants that can still be read, if any, and script.grants.revoke fails)}", + "{} the file access people allowed scripts with Always in a file dialog, kept in Script Grants.json next to the settings: each for one script file with one text and the files it includes (their SHA-256), so a changed or moved script, or a changed included file, has none, and with the SHA-256 of each source the run that kept it evaluated (files $.evalFile ran, strings given to eval and Function; at most 256), so a run loses it before it evaluates other code, or when its named engine holds code the grant was not kept for; at most 4096 → {grants: [{script: the script file's path, sha256, code: [SHA-256 of each evaluated source, of its UTF-16 code units in little-endian order], path: the file or folder allowed, write: it may be written, folder: the grant is a folder's, with everything in it (a file's grant is its own path only)}], file: the grants file's path | null (a session without a settings folder, and the web), error?: why the grants file cannot be read or changed, when it is there and cannot be read, is over 4 MiB, is not a version 1 grants file, holds a grant that is not well formed or more than 4096 grants, or its lock cannot be taken (grants then lists the well-formed grants that can still be read, if any, or is empty when the lock cannot be taken, as the file is then not read; script.grants.revoke fails)}", always, grants ), diff --git a/crates/engine/src/script/files.rs b/crates/engine/src/script/files.rs index 191f1c52e0..e023e83b45 100644 --- a/crates/engine/src/script/files.rs +++ b/crates/engine/src/script/files.rs @@ -1065,7 +1065,8 @@ fn lock_store(_: &Path) -> std::io::Result { /// its text, the path and whether it may be written (`script.grants`), as [`read_store`] reads /// them, and the error when the file is there and [`try_read_store`] refuses it (it cannot be read, /// is too large, is not a grants file of this version, or holds a grant that is not well formed or -/// more grants than may be kept) or its lock cannot be taken, which also refuses a change. +/// more grants than may be kept) or its lock cannot be taken, which also refuses a change. When the +/// lock cannot be taken the file is not read, and the list is empty. pub(crate) fn stored_grants(data_dir: &Path) -> (Vec, Option) { let store = data_dir.with_file_name(GRANTS_FILE); let _lock = match lock_store(&store) { diff --git a/crates/ui-egui/src/prefs_dialog/script_access.rs b/crates/ui-egui/src/prefs_dialog/script_access.rs index f1f8fa4416..78a9969f9e 100644 --- a/crates/ui-egui/src/prefs_dialog/script_access.rs +++ b/crates/ui-egui/src/prefs_dialog/script_access.rs @@ -41,7 +41,7 @@ const WHOLE: [(&str, &str); 2] = [("script", "wholeScript"), ("path", "wholePath /// (`wholeScript` and `wholePath`) for `script.grants.revoke`, and shows them (`script` and `path`) /// as `script.grants` names them to the request that opened the dialog ([`as_listed`]). When the /// grants file cannot be read or changed, its error goes in the field [`ERROR`], with the rows of the -/// grants that could still be read. +/// grants that could still be read (none when its lock cannot be taken). pub(super) fn load(app: &mut VectorcraftApp, fields: &mut Map) { fields.remove(ERROR); match vectorcraft_engine::file_access::unconfined(|| app.session.execute("script.grants", &json!({}))) { diff --git a/docs/mcp.md b/docs/mcp.md index 45c66c077c..3cc36056ac 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -3062,9 +3062,11 @@ a script file, of a path, of both together, or with `all: true` every grant, and matched after its links are followed; under automation read roots, a path outside them is matched as given. While a script runs it is refused with the busy error, as the run keeps the grants it started with. A grants file that is there but cannot be read is left as it is: `script.grants.revoke` fails, and a grant picked with Always is not kept. For such a -file, and one that is over 4 MiB, is not a version 1 grants file, holds a grant that is not well formed or more than -4096 grants, or whose lock cannot be taken, `script.grants` gives the reason in `error` and lists the well-formed grants -it can still read. Preferences › General › Script File Access shows that error. A script cannot run either command. +file, and one that is over 4 MiB, is not a version 1 grants file, or holds a grant that is not well formed or more than +4096 grants, `script.grants` gives the reason in `error` and lists the well-formed grants it can still read. When the +grants file's lock cannot be taken, `script.grants` gives the reason in `error` and does not read the file, so `grants` +is empty even when the file holds grants. Preferences › General › Script File Access shows that error. A script cannot +run either command. ```json {"name":"run_command","arguments":{"command":"script.grants.revoke","params":{"all":true}}} From c7108b22890f85849f0ef605c00e13678c4a639b Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 22 Nov 2026 17:57:57 -0800 Subject: [PATCH 071/151] Script File Access: name the whole path in Revoke's tooltip and description A row shows at most 1,024 characters of a script or path, so two grants whose paths differ only after that showed the same text in the row, its tooltip and the Revoke button's screen-reader description. The tooltips and the description now give the whole path, with control and bidirectional characters still written as escapes; the row label stays shortened. --- .../ui-egui/src/prefs_dialog/script_access.rs | 22 ++++++++++----- crates/ui-egui/src/prefs_dialog/tests.rs | 28 +++++++++++++++++++ 2 files changed, 43 insertions(+), 7 deletions(-) diff --git a/crates/ui-egui/src/prefs_dialog/script_access.rs b/crates/ui-egui/src/prefs_dialog/script_access.rs index 78a9969f9e..80deee700f 100644 --- a/crates/ui-egui/src/prefs_dialog/script_access.rs +++ b/crates/ui-egui/src/prefs_dialog/script_access.rs @@ -102,6 +102,13 @@ pub(super) fn shown(path: &str) -> String { permissions::display_text(path, MAX_SHOWN_PATH) } +/// `path` as a row's tooltip and its Revoke button's screen-reader description give it: control and +/// bidirectional formatting characters written as escapes, and whole, so two paths that a row shows +/// alike stay apart. +fn shown_whole(path: &str) -> String { + permissions::display_text(path, usize::MAX) +} + /// A kept script or path as `script.grants` names it to the request being served: whole where that /// request may read it, else its file name alone (empty for a path that ends in no name). pub(crate) fn as_listed(path: &str) -> &str { @@ -185,15 +192,16 @@ pub(super) fn show(ui: &mut egui::Ui, app: &mut VectorcraftApp, d: &mut Dialog) let size = egui::vec2(ui.available_width(), ROW_HEIGHT); match *line { Line::Script(i) => { - let script = shown(rows[i]["script"].as_str().unwrap_or_default()); + let script = rows[i]["script"].as_str().unwrap_or_default(); ui.allocate_ui_with_layout(size, egui::Layout::left_to_right(egui::Align::Center), |ui| { - let text = egui::RichText::new(&script).color(t.text_strong).size(12.0); - ui.add(egui::Label::new(text).truncate()).on_hover_text(&script); + let text = egui::RichText::new(shown(script)).color(t.text_strong).size(12.0); + ui.add(egui::Label::new(text).truncate()).on_hover_text(shown_whole(script)); }); } Line::Row(i) => { let row = &rows[i]; - let (script, path) = (shown(row["script"].as_str().unwrap_or_default()), shown(row["path"].as_str().unwrap_or_default())); + let (script, path) = (row["script"].as_str().unwrap_or_default(), row["path"].as_str().unwrap_or_default()); + let (script, path, path_whole) = (shown_whole(script), shown(path), shown_whole(path)); ui.allocate_ui_with_layout(size, egui::Layout::left_to_right(egui::Align::Center), |ui| { ui.add_space(12.0); // The path, then the access and the Revoke button at the right. @@ -202,7 +210,7 @@ pub(super) fn show(ui: &mut egui::Ui, app: &mut VectorcraftApp, d: &mut Dialog) let cell = |width: f32| egui::vec2(width, ROW_HEIGHT); ui.allocate_ui_with_layout(cell(path_width), egui::Layout::left_to_right(egui::Align::Center), |ui| { ui.set_width(path_width); - ui.add(egui::Label::new(egui::RichText::new(&path).color(t.text)).truncate()).on_hover_text(&path); + ui.add(egui::Label::new(egui::RichText::new(&path).color(t.text)).truncate()).on_hover_text(&path_whole); }); ui.add_space(12.0); ui.allocate_ui_with_layout(cell(access_width), egui::Layout::left_to_right(egui::Align::Center), |ui| { @@ -212,11 +220,11 @@ pub(super) fn show(ui: &mut egui::Ui, app: &mut VectorcraftApp, d: &mut Dialog) }); let button = widgets::secondary_button(ui, tl!("Revoke")); // A screen reader names the script and the path along with the button. - ui.ctx().accesskit_node_builder(button.id, |node| node.set_description(format!("{script}: {path}"))); + ui.ctx().accesskit_node_builder(button.id, |node| node.set_description(format!("{script}: {path_whole}"))); if focus == Some(i) { button.request_focus(); } - if button.on_hover_text(&path).clicked() { + if button.on_hover_text(&path_whole).clicked() { revoke_at = Some(i); } }); diff --git a/crates/ui-egui/src/prefs_dialog/tests.rs b/crates/ui-egui/src/prefs_dialog/tests.rs index 2ee1cf2663..990bf57b3d 100644 --- a/crates/ui-egui/src/prefs_dialog/tests.rs +++ b/crates/ui-egui/src/prefs_dialog/tests.rs @@ -3255,6 +3255,34 @@ fn script_file_access_shows_paths_as_plain_text() { let _ = std::fs::remove_dir_all(store.parent().unwrap()); } +/// Two paths that differ only after the characters a row shows keep their whole paths in the Revoke +/// buttons' screen-reader descriptions, so each button names the grant it removes. +#[test] +fn script_file_access_revoke_names_the_whole_path() { + let mut long = std::env::temp_dir().join("vc-ui-prefs-grants-nowhere"); + for _ in 0..11 { + long.push("d".repeat(100)); + } + let (script, one, two) = (long.with_file_name("a.jsx"), long.join("1.txt"), long.join("2.txt")); + let (mut a, store) = app_with_grants("grants-long", json!([grant(&script, &one, "1", false, false), grant(&script, &two, "1", false, false)])); + open(&mut a, Some("General")); + let ctx = fonts_context(); + ctx.enable_accesskit(); + script_access_in_view(&mut a, &ctx, "Revoke"); + let screen_rect = Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1200.0, 900.0))); + let raw = egui::RawInput { screen_rect, time: Some(ctx.input(|i| i.time) + 0.25), ..Default::default() }; + let mut out = ctx.run_ui(raw, |ui| show(&mut a, ui.ctx())); + out.textures_delta.clear(); + let nodes = out.platform_output.accesskit_update.map(|u| u.nodes).unwrap_or_default(); + let descriptions: Vec = + nodes.iter().filter(|(_, n)| n.label() == Some("Revoke")).filter_map(|(_, n)| n.description().map(str::to_string)).collect(); + for path in [&one, &two] { + let whole = path.to_string_lossy(); + assert!(descriptions.iter().any(|d| d.ends_with(&*whole)), "{whole} in {descriptions:?}"); + } + let _ = std::fs::remove_dir_all(store.parent().unwrap()); +} + fn description_fits(ui: &egui::Ui, text: &str) -> bool { let mut job = egui::text::LayoutJob::simple(text.to_string(), egui::FontId::proportional(11.5), egui::Color32::WHITE, 530.0); job.wrap.max_rows = 3; From ebebe8c02aaff94b542794ecb1702042cc9e9a24 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 24 Nov 2026 17:32:58 -0800 Subject: [PATCH 072/151] Retype: the installed-font search picks the faces to compare on its own thread RetypeRun::prepare no longer reads font files: the loaded faces to compare first are picked when the search runs, off the UI thread. The Retype Fonts list leaves room for installed fonts by the loaded matches it lists, so a face that matches only as combining marks takes no place. --- crates/engine/src/cmd/retype_fonts.rs | 5 +- crates/engine/src/cmd/retype_installed.rs | 52 +++++++++++++------ .../engine/src/cmd/retype_installed_tests.rs | 29 +++++++---- 3 files changed, 57 insertions(+), 29 deletions(-) diff --git a/crates/engine/src/cmd/retype_fonts.rs b/crates/engine/src/cmd/retype_fonts.rs index dfd14e3ee6..e0af549da6 100644 --- a/crates/engine/src/cmd/retype_fonts.rs +++ b/crates/engine/src/cmd/retype_fonts.rs @@ -115,8 +115,9 @@ pub(super) fn rank_fonts( let mut ranked: Vec = vec![]; rank(&index, shapes, &mut ranked); // The installed fonts not loaded yet: those whose glyphs match a shape, of the version their - // family and style name gives, up to 96 fonts listed in all. - let room = MAX_COUNT.saturating_sub(ranked.len()); + // family and style name gives, up to 96 fonts listed in all. A font that matches only as + // combining marks is not listed, so it takes no place. + let room = MAX_COUNT.saturating_sub(ranked.iter().filter(|r| r.character).count()); let found = if let Some(handed) = handed { handed } else if !search_installed { diff --git a/crates/engine/src/cmd/retype_installed.rs b/crates/engine/src/cmd/retype_installed.rs index d63c777886..eda6e1105b 100644 --- a/crates/engine/src/cmd/retype_installed.rs +++ b/crates/engine/src/cmd/retype_installed.rs @@ -494,9 +494,10 @@ fn load(db: &FontDb, face: &Arc) -> Arc { } /// A search of the installed fonts made away from its command, so the app can run it off the UI -/// thread with a Cancel. [`RetypeRun::prepare`] takes the selected shapes and the loaded faces to -/// compare from the session, checking the params as the command checks them; [`RetypeSearch::run`] -/// compares them and searches the installed fonts on any thread, loading the faces that match; and +/// thread with a Cancel. [`RetypeRun::prepare`] takes the selected shapes and the document from the +/// session, checking the params as the command checks them; [`RetypeSearch::run`] picks the loaded +/// faces to compare, compares them and searches the installed fonts on any thread, loading the +/// faces that match; and /// [`RetypeFound::hand_in`] gives what it found to the command, which then runs with /// [`RetypeRun::params`] and compares those faces as its own search would, without reading the /// installed fonts again. @@ -517,11 +518,34 @@ pub struct RetypeSearch { doc: u64, /// The shapes to match, and the loaded faces they are compared with first. shapes: Vec, - faces: Vec>, + faces: Faces, /// `type.retype`'s tolerance (0 for `type.retypeFonts`). tolerance: f64, } +/// The loaded faces a [`RetypeSearch`] compares first. +enum Faces { + /// These faces. + #[cfg(test)] + Given(Vec>), + /// Those the command picks in `doc`: with `fonts` (`type.retype`'s `fonts` param), the faces of + /// those families and of the document's live type ([`super::candidate_faces`]), and without, the + /// faces `type.retypeFonts` lists ([`super::fonts::listed_faces`]). They are picked on the + /// search's thread, since a family not loaded yet is read from its files. + Of { doc: Arc, fonts: Option> }, +} + +impl Faces { + fn get(&self, db: &FontDb) -> Vec> { + match self { + #[cfg(test)] + Faces::Given(faces) => faces.clone(), + Faces::Of { doc, fonts: Some(fonts) } => super::candidate_faces(db, doc, fonts), + Faces::Of { doc, fonts: None } => super::fonts::listed_faces(db, doc), + } + } +} + /// A shape a [`RetypeSearch`] compares, as `type.retype` matches it ([`super::shape_parts`]): its /// path, its contour groups when it may hold several glyphs, its fill rule when it has a visible /// fill (`Some(nonzero)`), and whether it paints its overlaps once ([`super::paints_once`]). @@ -583,12 +607,8 @@ impl RetypeRun { /// The search `command` (`type.retype` or `type.retypeFonts`) with params `p` makes in the /// active document. None when it reads no installed font: `installed` is false, or no shape has /// a glyph's key. An error where the command fails on its params or on the selection. + /// The faces to compare are picked when the search runs. pub fn prepare(s: &Session, command: &str, p: &Value) -> Result> { - Self::prepare_in(s, command, p, FontDb::global()) - } - - /// [`RetypeRun::prepare`] with the fonts of `db`. - fn prepare_in(s: &Session, command: &str, p: &Value, db: &FontDb) -> Result> { let (command, fonts, tolerance) = match command { "type.retype" => ("type.retype", Some(super::fonts_param(p)?), super::tolerance_param(p)?), "type.retypeFonts" => { @@ -626,10 +646,7 @@ impl RetypeRun { if keys.is_empty() && near.is_empty() { return Ok(None); } - let faces = match &fonts { - Some(fonts) => super::candidate_faces(db, &st.doc, fonts), - None => super::fonts::listed_faces(db, &st.doc), - }; + let faces = Faces::Of { doc: st.doc.clone(), fonts }; Ok(Some(RetypeRun { params: p.clone(), doc: st.uid, @@ -677,9 +694,10 @@ impl RetypeSearch { /// [`RetypeSearch::run`] with the fonts of `db`. fn run_in(&self, db: &FontDb) -> Result { + let picked = self.faces.get(db); let installed = if self.command == "type.retypeFonts" { let shapes: Vec<&BezPath> = self.shapes.iter().map(|s| &s.path).collect(); - let (ranked, mut found) = super::fonts::rank_fonts(db, self.faces.clone(), &shapes, true, None)?; + let (ranked, mut found) = super::fonts::rank_fonts(db, picked, &shapes, true, None)?; // The loaded faces that match are handed in too, ahead of the installed ones found: // loading those can move a loaded face past the 96 the command lists. let mut faces: Vec> = ranked.iter().map(|r| r.face().clone()).collect(); @@ -695,7 +713,7 @@ impl RetypeSearch { let tolerance = self.tolerance; let sought: Vec = self.shapes.iter().map(Shape::sought).collect(); let (keys, near) = keys_of(&sought, tolerance); - let index = RetypeIndex::build_near(db, self.faces.iter().cloned(), &keys, &near); + let index = RetypeIndex::build_near(db, picked.iter().cloned(), &keys, &near); let parts: Vec>> = self.shapes.iter().map(|s| super::shape_parts(&s.path, &s.groups, s.fill, s.once, &[&index], tolerance)).collect(); let left: Vec = sought.iter().zip(&parts).filter(|(_, p)| p.is_empty()).map(|(s, _)| *s).collect(); @@ -709,13 +727,13 @@ impl RetypeSearch { } // The loaded faces past the ones compared first, then the installed fonts for what // none of them matches; the command takes both from what is handed in. - let compared: Vec = self.faces.iter().map(|f| f.id()).collect(); + let compared: Vec = picked.iter().map(|f| f.id()).collect(); // Every face loaded now is compared, among the first ones or with the rest. let scanned: Vec = compared.iter().copied().chain(db.loaded_faces().iter().map(|f| f.id())).collect(); // A split shape's glyphs may be spread over the faces compared first and the others. // Near matching spends an index's comparison budget, so with a tolerance the faces // compared first are indexed again for each search that has a split shape to look for. - let again = |needed: bool| (needed && tolerance > 0.0).then(|| RetypeIndex::build_near(db, self.faces.iter().cloned(), &keys, &near)); + let again = |needed: bool| (needed && tolerance > 0.0).then(|| RetypeIndex::build_near(db, picked.iter().cloned(), &keys, &near)); let fresh = again(left.iter().any(|s| !s.groups.is_empty())); let (rest, done, kept) = loaded_rest_for(db, &left, &[fresh.as_ref().unwrap_or(&index)], tolerance, &compared)?; let left: Vec = left.into_iter().zip(done).filter(|(_, done)| !done).map(|(s, _)| s).collect(); diff --git a/crates/engine/src/cmd/retype_installed_tests.rs b/crates/engine/src/cmd/retype_installed_tests.rs index da5017878c..8db2c1ab12 100644 --- a/crates/engine/src/cmd/retype_installed_tests.rs +++ b/crates/engine/src/cmd/retype_installed_tests.rs @@ -254,7 +254,13 @@ fn a_run_away_from_the_list_hands_in_the_loaded_faces_that_match_with_the_instal vectorcraft_text::test_fonts::named_copy(false, ("Retype Loaded List", "Regular", "Version 1.000", "RetypeLoadedList-Regular")).unwrap(), ); let loaded: Vec<_> = db.loaded_faces().into_iter().filter(|f| f.family == "Retype Loaded List").collect(); - let search = super::RetypeSearch { command: "type.retypeFonts", doc: 1, shapes: whole(glyphs(&db, "Rx")), faces: loaded.clone(), tolerance: 0.0 }; + let search = super::RetypeSearch { + command: "type.retypeFonts", + doc: 1, + shapes: whole(glyphs(&db, "Rx")), + faces: super::Faces::Given(loaded.clone()), + tolerance: 0.0, + }; let found = search.run_in(&db).unwrap(); let families: Vec<&str> = found.installed.faces.iter().map(|f| f.family.as_str()).collect(); // The loaded face first, then the installed one, each once. @@ -308,26 +314,26 @@ fn a_run_away_from_the_command_loads_the_faces_it_finds() { s.execute("select.set", &json!({"ids": ids})).unwrap(); // Off: nothing to run. for cmd in ["type.retype", "type.retypeFonts"] { - assert!(super::RetypeRun::prepare_in(&s, cmd, &json!({"installed": false}), &db).unwrap().is_none()); + assert!(super::RetypeRun::prepare(&s, cmd, &json!({"installed": false})).unwrap().is_none()); } // The command's params are checked as it checks them. - assert!(super::RetypeRun::prepare_in(&s, "type.retypeFonts", &json!({"count": 0}), &db).is_err()); - assert!(super::RetypeRun::prepare_in(&s, "type.retype", &json!({"fonts": 1}), &db).is_err()); - assert!(super::RetypeRun::prepare_in(&s, "type.text", &json!({}), &db).is_err()); + assert!(super::RetypeRun::prepare(&s, "type.retypeFonts", &json!({"count": 0})).is_err()); + assert!(super::RetypeRun::prepare(&s, "type.retype", &json!({"fonts": 1})).is_err()); + assert!(super::RetypeRun::prepare(&s, "type.text", &json!({})).is_err()); // An unknown key fails before any search, as the command fails on it. for cmd in ["type.retype", "type.retypeFonts"] { - let e = super::RetypeRun::prepare_in(&s, cmd, &json!({"typo": true}), &db).err().map(|e| e.to_string()).unwrap_or_default(); + let e = super::RetypeRun::prepare(&s, cmd, &json!({"typo": true})).err().map(|e| e.to_string()).unwrap_or_default(); assert!(e.contains("typo"), "{cmd}: {e}"); assert!(s.execute(cmd, &json!({"typo": true})).is_err()); } // Retype: the loaded Source Sans 3 matches both shapes, so no installed file is read. - let run = super::RetypeRun::prepare_in(&s, "type.retype", &json!({}), &db).unwrap().unwrap(); + let run = super::RetypeRun::prepare(&s, "type.retype", &json!({})).unwrap().unwrap(); assert_eq!(run.command(), "type.retype"); assert_eq!(run.params(), &json!({})); assert_eq!(run.run_in(&db).unwrap().json(), json!({"read": 0, "skipped": 0})); assert!(unloaded(&db, "Retype Copy X")); // The list compares every installed face: the copy is read and loaded. - let run = super::RetypeRun::prepare_in(&s, "type.retypeFonts", &json!({"count": 5}), &db).unwrap().unwrap(); + let run = super::RetypeRun::prepare(&s, "type.retypeFonts", &json!({"count": 5})).unwrap().unwrap(); assert_eq!(run.params(), &json!({"count": 5})); assert!(run.current(&s)); let found = run.run_in(&db).unwrap(); @@ -747,7 +753,8 @@ fn a_run_away_from_the_command_hands_in_the_loaded_faces_past_the_ones_compared_ // The Inter copies are compared first: none matches, and the copy loaded after them does. let faces: Vec<_> = db.loaded_faces().into_iter().filter(|f| f.family.starts_with("Retype Run Rest Inter")).collect(); assert_eq!(faces.len(), vectorcraft_text::retype::MAX_FACES); - let search = super::RetypeSearch { command: "type.retype", doc: 1, shapes: whole(shapes.clone()), faces, tolerance: 0.0 }; + let search = + super::RetypeSearch { command: "type.retype", doc: 1, shapes: whole(shapes.clone()), faces: super::Faces::Given(faces), tolerance: 0.0 }; let found = search.run_in(&db).unwrap(); assert!(found.installed.faces.iter().any(|f| f.family == "Retype Run Rest 0"), "the loaded copy is handed in"); assert_eq!((found.installed.read, found.installed.skipped), (0, 0), "no installed file is read for it"); @@ -756,7 +763,9 @@ fn a_run_away_from_the_command_hands_in_the_loaded_faces_past_the_ones_compared_ // A face compared first that matches is handed in too, as loading others may move it past // the faces the command compares first. let copy: Vec<_> = db.loaded_faces().into_iter().filter(|f| f.family == "Retype Run Rest 0").collect(); - let found = super::RetypeSearch { command: "type.retype", doc: 1, shapes: whole(shapes), faces: copy, tolerance: 0.0 }.run_in(&db).unwrap(); + let found = super::RetypeSearch { command: "type.retype", doc: 1, shapes: whole(shapes), faces: super::Faces::Given(copy), tolerance: 0.0 } + .run_in(&db) + .unwrap(); assert_eq!(found.installed.faces.first().map(|f| f.family.as_str()), Some("Retype Run Rest 0")); } From 986da7d0b43a25cf52d40e6304166620a55d390d Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 24 Nov 2026 18:06:50 -0800 Subject: [PATCH 073/151] Scripts: assigning undefined to Document.selection throws and keeps the selection Document.selection treated undefined like null and cleared the selection. It now throws a TypeError for undefined, as for any value that is not a page item, a list of them, null or [], and leaves the selection as it was. --- crates/engine/src/script/dom.rs | 2 +- crates/engine/src/tests/script_dom.rs | 12 ++++++++++++ docs/mcp.md | 6 +++--- 3 files changed, 16 insertions(+), 4 deletions(-) diff --git a/crates/engine/src/script/dom.rs b/crates/engine/src/script/dom.rs index ea76e59fdf..304ba29878 100644 --- a/crates/engine/src/script/dom.rs +++ b/crates/engine/src/script/dom.rs @@ -1236,7 +1236,7 @@ fn selection_of(h: &Host, uid: u64) -> Answer { /// `[]`. Every one must be an object of that document that can be selected. fn selection_ids(h: &Host, doc: Doc, v: &Data) -> std::result::Result, HostError> { let list: Vec<&Data> = match v { - Data::Null | Data::Undefined => Vec::new(), + Data::Null => Vec::new(), Data::Array(a) if a.len() > MAX_LISTED => return Err(HostError::Range(format!("a selection takes at most {MAX_LISTED} objects"))), Data::Array(a) => a.iter().collect(), d => vec![d], diff --git a/crates/engine/src/tests/script_dom.rs b/crates/engine/src/tests/script_dom.rs index 60e3a71521..3d6c9af7b9 100644 --- a/crates/engine/src/tests/script_dom.rs +++ b/crates/engine/src/tests/script_dom.rs @@ -825,6 +825,18 @@ fn assigning_the_same_objects_clears_the_key_and_guides() { assert!(s.active().unwrap().selection.guides.is_empty()); } +/// Assigning `undefined` or a value that is not a page item to the selection throws and keeps it. +#[test] +fn assigning_undefined_to_the_selection_throws_and_keeps_it() { + let (mut s, a, b) = doc(); + s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap(); + for source in ["var u; app.activeDocument.selection = u;", "app.activeDocument.selection = undefined;", "app.activeDocument.selection = 1;"] { + let e = failure(&mut s, source); + assert!(e.contains("TypeError"), "{source}: {e}"); + assert_eq!(s.active().unwrap().selection.objects, vec![a, b], "{source}"); + } +} + #[test] fn a_page_item_with_a_large_id_keeps_its_id() { let mut s = Session::new(); diff --git a/docs/mcp.md b/docs/mcp.md index 092943ba56..ab430b8183 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2717,9 +2717,9 @@ app through the global object `vc`, and writes to the Script Console and runs ot the page's axes, so a rotated object then reads back the size that was set. `index` and `getByName` throw `Not found`; and `app.activeDocument` with no document open throws `No active document`. `Document.selection` takes one page item, - a list of at most 10,000, `null` or `[]`, and an object that cannot be selected throws `Cannot select` with - nothing changed. While View › Guides › Lock Guides is on, a path made into a guide cannot be selected this way or - with `selected`. `getIsFileOpen` compares the path with the open documents' files as text (in a Windows path, + a list of at most 10,000, `null` or `[]`. Any other value, `undefined` included, throws a `TypeError`, and an + object that cannot be selected throws `Cannot select`, each with nothing changed. While View › Guides › Lock + Guides is on, a path made into a guide cannot be selected this way or with `selected`. `getIsFileOpen` compares the path with the open documents' files as text (in a Windows path, letter case is ignored and `\` matches `/`) and does not resolve the path it is given. A document counts only when 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, From 468b434c09755156dc01ff7a22cf8f79bd15f763 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 24 Nov 2026 23:52:00 -0800 Subject: [PATCH 074/151] Plug-ins: a JavaScript plug-in's parameters keep their declaration order Loading a JavaScript plug-in read its JSON into a map that sorts its keys and wrote it out again before parsing the manifest, so `params` and each command's `params` reached dialogs in alphabetical order. The manifest is now parsed from the plug-in's own JSON (`Manifest::parse_text`), with its size still counted without `script` and `source`, and a `.vcplugin` read from a folder has `source` added to its own text instead of being written out again. --- crates/plugins/src/js.rs | 28 ++++++++++++++++++++++--- crates/plugins/src/manifest.rs | 7 +++++++ crates/plugins/src/registry.rs | 37 +++++++++++++++++++++++++++++++--- 3 files changed, 66 insertions(+), 6 deletions(-) diff --git a/crates/plugins/src/js.rs b/crates/plugins/src/js.rs index e6b13e73fa..186d3f4296 100644 --- a/crates/plugins/src/js.rs +++ b/crates/plugins/src/js.rs @@ -30,7 +30,7 @@ use serde_json::{Map, Value}; use vectorcraft_js::{Data, HostError, HostItem, JsValue, LimitKind, Progress, Realm, RunError, RunErrorKind}; use crate::host::{Deadline, LOG_BAD_LEVEL, LOG_DROPPED, LOG_WRITTEN, Report, Run}; -use crate::manifest::{Manifest, Runtime}; +use crate::manifest::{MAX_MANIFEST_BYTES, Manifest, Runtime}; use crate::permissions::{self, Permission}; use crate::runtime::SELECTION_TOO_LARGE; use crate::{Error, Limits, Result}; @@ -134,8 +134,14 @@ pub(crate) fn read_bundle(bytes: &[u8]) -> Result<(Manifest, Script)> { if source.len() > MAX_SCRIPT_BYTES { return Err(Error::Module(format!("{} is {} bytes (limit {})", name, source.len(), MAX_SCRIPT_BYTES))); } - let manifest = serde_json::to_vec(&map).map_err(|e| Error::Manifest(e.to_string()))?; - let manifest = Manifest::parse(&manifest)?; + // The manifest is read from `bytes`, so `params` keep their order; its size is counted + // without `script` and `source`. + let size = serde_json::to_vec(&map).map_err(|e| Error::Manifest(e.to_string()))?.len(); + if size > MAX_MANIFEST_BYTES { + return Err(Error::Manifest(format!("manifest is {size} bytes (limit {MAX_MANIFEST_BYTES})"))); + } + let text = std::str::from_utf8(bytes).map_err(|_| Error::Manifest("manifest is not UTF-8".into()))?; + let manifest = Manifest::parse_text(text)?; if let Err(e) = vectorcraft_js::parse(&source, &options()) { let named = Named { id: &manifest.id, script: &name }; return Err(Error::Module(located(&permissions::display_text(&e.message, MAX_ERROR_TEXT), &named, Some((e.line, e.column))))); @@ -481,6 +487,22 @@ mod tests { assert_ne!(a.hash(), b.hash()); } + /// The parameters, and a command's, keep the order the plug-in's JSON declares them in. + #[test] + fn params_keep_their_declaration_order() { + let num = r#"{"type": "number", "min": 0, "max": 10, "default": 1}"#; + let text = format!( + r#"{{"id": "test.js.order", "name": "JS test", "kind": "filter", "runtime": "js", "script": "test.js", + "params": {{"z": {num}, "a": {num}, "m": {num}}}, + "commands": [{{"id": "go", "label": "Go", "params": {{"y": {num}, "b": {num}}}}}], + "source": "function run(i) {{ return i; }}"}}"# + ); + let (manifest, _) = super::read_bundle(text.as_bytes()).unwrap(); + let names = |p: &[(String, crate::manifest::Param)]| p.iter().map(|(k, _)| k.clone()).collect::>(); + assert_eq!(names(&manifest.params), ["z", "a", "m"]); + assert_eq!(names(&manifest.commands[0].params), ["y", "b"]); + } + #[test] fn script_names_stay_in_the_manifest_s_folder() { for ok in ["tint.js", "Tint Tool.JS", "a.b.js"] { diff --git a/crates/plugins/src/manifest.rs b/crates/plugins/src/manifest.rs index 570f29aa72..9e84f2a2f2 100644 --- a/crates/plugins/src/manifest.rs +++ b/crates/plugins/src/manifest.rs @@ -477,6 +477,13 @@ impl Manifest { return Err(Error::Manifest(format!("manifest is {} bytes (limit {MAX_MANIFEST_BYTES})", bytes.len()))); } let text = std::str::from_utf8(bytes).map_err(|_| Error::Manifest("manifest is not UTF-8".into()))?; + Manifest::parse_text(text) + } + + /// [`Manifest::parse`] without its size limit, for JSON that holds other keys besides the + /// manifest's (a JavaScript plug-in's `source`), whose caller checks the manifest's size. Keys + /// the manifest doesn't declare are ignored, and `params` keep the order the text gives them. + pub(crate) fn parse_text(text: &str) -> Result { if serde_json::from_str::(text).is_ok_and(|v| v.get("paintOutput").is_some_and(|p| *p != Value::Bool(true))) { return Err(Error::Manifest("`paintOutput` may only be true".into())); } diff --git a/crates/plugins/src/registry.rs b/crates/plugins/src/registry.rs index 01a1f7731e..76796cbe84 100644 --- a/crates/plugins/src/registry.rs +++ b/crates/plugins/src/registry.rs @@ -219,7 +219,7 @@ fn read_js_package_with( use serde_json::Value; let manifest_limits = Limits { max_module_bytes: crate::manifest::MAX_MANIFEST_BYTES, ..Limits::default() }; let bytes = read_module(path, &manifest_limits, || {})?; - let mut map: serde_json::Map = serde_json::from_slice(&bytes).map_err(|e| Error::Manifest(format!("{}: {e}", path.display())))?; + let map: serde_json::Map = serde_json::from_slice(&bytes).map_err(|e| Error::Manifest(format!("{}: {e}", path.display())))?; if !crate::js::is_js(&map) { return Err(Error::Manifest(crate::js::NOT_JS.into())); } @@ -232,8 +232,17 @@ fn read_js_package_with( let script_limits = Limits { max_module_bytes: crate::js::MAX_SCRIPT_BYTES, ..Limits::default() }; let source = read_module(&file, &script_limits, opening)?; let source = String::from_utf8(source).map_err(|_| Error::Module("the script is not UTF-8 text".into()))?; - map.insert("source".into(), Value::String(source)); - serde_json::to_vec(&map).map_err(|e| Error::Manifest(e.to_string())) + // `source` is added to the manifest's own text, so its keys keep their order. The text parsed as + // an object that has `runtime`, so its last character other than white space is its closing `}`. + let end = bytes.iter().rposition(|b| !b.is_ascii_whitespace()).filter(|&i| bytes[i] == b'}'); + let end = end.ok_or_else(|| Error::Manifest(format!("{}: not a JSON object", path.display())))?; + let source = serde_json::to_vec(&Value::String(source)).map_err(|e| Error::Manifest(e.to_string()))?; + let mut out = Vec::with_capacity(bytes.len() + source.len() + 12); + out.extend_from_slice(&bytes[..end]); + out.extend_from_slice(b",\"source\":"); + out.extend_from_slice(&source); + out.push(b'}'); + Ok(out) } /// The bytes of the module file at `path`. A path that doesn't name a regular file is refused @@ -704,6 +713,28 @@ mod tests { assert!(!opened.get(), "the script was opened"); } + /// A manifest file's parameters keep their declaration order through the package it is read + /// into, which is its own text with `source` added. + #[cfg(not(target_arch = "wasm32"))] + #[test] + fn a_javascript_package_keeps_the_manifest_s_order() { + let dir = test_dir("js-order"); + let num = r#"{"type": "number", "min": 0, "max": 10, "default": 1}"#; + let text = format!( + "{{\"id\": \"order\", \"name\": \"JS\", \"kind\": \"filter\", \"runtime\": \"js\", \"script\": \"f.js\", \"params\": {{\"z\": {num}, \"a\": {num}}}}}\n" + ); + let path = dir.join("order.vcplugin"); + std::fs::write(&path, &text).unwrap(); + std::fs::write(dir.join("f.js"), "function run(i) { return i; }").unwrap(); + let bytes = read_js_package(&path, &|_| Ok(())); + std::fs::remove_dir_all(&dir).unwrap(); + let bytes = bytes.unwrap(); + let expected = format!("{},\"source\":\"function run(i) {{ return i; }}\"}}", text.trim_end().strip_suffix('}').unwrap()); + assert_eq!(String::from_utf8_lossy(&bytes), expected); + let (manifest, _) = crate::js::read_bundle(&bytes).unwrap(); + assert_eq!(manifest.params.iter().map(|(k, _)| k.as_str()).collect::>(), ["z", "a"]); + } + /// A folder load reports a subfolder, a named pipe and a link to a named pipe with `.wasm` /// names as not files, and goes on. #[cfg(unix)] From b3430b7f825a832fe09c8b85459d8ea9440d7df5 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 25 Nov 2026 04:45:41 -0800 Subject: [PATCH 075/151] Script File Access: no row for a grant with an empty script or path script.grants lists a kept grant whose script or path is an empty string, but script.grants.revoke does not take an empty path, so its Revoke button could not remove it. Such a grant now has no row. --- .../ui-egui/src/prefs_dialog/script_access.rs | 6 +++++- crates/ui-egui/src/prefs_dialog/tests.rs | 19 +++++++++++++++++++ 2 files changed, 24 insertions(+), 1 deletion(-) diff --git a/crates/ui-egui/src/prefs_dialog/script_access.rs b/crates/ui-egui/src/prefs_dialog/script_access.rs index e8e70ec1eb..bdf4b128f5 100644 --- a/crates/ui-egui/src/prefs_dialog/script_access.rs +++ b/crates/ui-egui/src/prefs_dialog/script_access.rs @@ -77,7 +77,8 @@ pub(super) fn load(app: &mut VectorcraftApp) -> Option { /// The rows for the grants `grants` lists: one for each script and path, sorted by script and then by path, with the /// widest access any kept version of the pair has (`folder`, then `write`, then `read`) and how many versions are -/// kept. A grant without a script or a path is left out. +/// kept. A grant without a script or a path, or with an empty one, which `script.grants.revoke` does not take, is +/// left out. fn rows(grants: &Value) -> Vec { let rank = |access: &str| match access { "folder" => 2, @@ -87,6 +88,9 @@ fn rows(grants: &Value) -> Vec { let mut pairs: BTreeMap<(&str, &str), (&'static str, usize)> = BTreeMap::new(); for g in grants.as_array().into_iter().flatten() { let (Some(script), Some(path)) = (g["script"].as_str(), g["path"].as_str()) else { continue }; + if script.is_empty() || path.is_empty() { + continue; + } let access = if g["folder"] == true { "folder" } else if g["write"] == true { diff --git a/crates/ui-egui/src/prefs_dialog/tests.rs b/crates/ui-egui/src/prefs_dialog/tests.rs index 02c9913b43..c148173378 100644 --- a/crates/ui-egui/src/prefs_dialog/tests.rs +++ b/crates/ui-egui/src/prefs_dialog/tests.rs @@ -833,6 +833,25 @@ fn script_file_access_shows_none_and_a_revoke_of_a_removed_row() { assert!(access_texts(&mut web).is_empty()); } +/// A kept grant with an empty script or path, which `script.grants` lists and `script.grants.revoke` does not take, +/// has no row. +#[test] +fn script_file_access_leaves_out_a_grant_with_an_empty_script_or_path() { + let dir = std::env::temp_dir().join("vc-ui-prefs-grants-nowhere"); + let (script, path) = (dir.join("a.jsx"), dir.join("out.txt")); + let grants = json!([ + grant(&script, &path, "1", false, false), + grant(&script, "".as_ref(), "1", false, false), + grant("".as_ref(), &path, "1", false, false) + ]); + let (mut a, store) = app_with_grants("grants-empty", grants); + assert_eq!(a.session.execute("script.grants", &json!({})).unwrap()["grants"].as_array().map(Vec::len), Some(3)); + open(&mut a, Some("General")); + let row = (script.to_string_lossy().into_owned(), path.to_string_lossy().into_owned(), "read".to_string(), 1); + assert_eq!(access_rows(&a), [row]); + let _ = std::fs::remove_dir_all(store.parent().unwrap()); +} + /// Preferences opened with a read root in force shows a script and a path outside it by their file /// names alone, as `script.grants` lists them, and `ui.inspect` names them the same way; Revoke /// still removes that pair's kept grants, both with the root in force and without it. From b0f74500eed52dda1b2d61012ddd6e8449a5f293 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 25 Nov 2026 05:07:46 -0800 Subject: [PATCH 076/151] Scripts: a native file with a tag id that is not a whole number opens A tag id in a native file that is negative, a fraction or text read as an error, so the whole file failed to open. It now reads as 0, and opening gives the tag a new id as it does for a missing or repeated id, with its name and value kept. The Scripts line in docs/target-app-parity.md now describes PageItem.tags and Document.tags separately: Document.tags reads, renames and deletes tags but its add throws. --- crates/doc/src/node/attributes.rs | 9 ++++++++- crates/engine/src/tests/script_tags.rs | 23 +++++++++++++++++++++++ docs/target-app-parity.md | 2 +- 3 files changed, 32 insertions(+), 2 deletions(-) diff --git a/crates/doc/src/node/attributes.rs b/crates/doc/src/node/attributes.rs index dca575c6f6..67d3d02308 100644 --- a/crates/doc/src/node/attributes.rs +++ b/crates/doc/src/node/attributes.rs @@ -58,7 +58,7 @@ pub struct ObjectTag { /// Distinct among the object's tags: a new tag takes an id from /// [`crate::Document::alloc_tag_id`], and deleting a tag raises the next node id above its id, /// so a deleted tag's id is not given out again. - #[serde(default)] + #[serde(default, deserialize_with = "lenient_tag_id")] pub id: u64, #[serde(default)] pub name: String, @@ -66,6 +66,13 @@ pub struct ObjectTag { pub value: String, } +/// Reading a native file never fails over a tag id that is not a whole number from 0 to +/// `u64::MAX` (a negative one, a fraction, text): it reads as 0, and +/// [`crate::Document::tidy_tags`] gives the tag a new id. +fn lenient_tag_id<'de, D: serde::Deserializer<'de>>(d: D) -> Result { + Ok(serde_json::Value::deserialize(d)?.as_u64().unwrap_or(0)) +} + impl ObjectAttributes { /// Keeps the tags within the limits: the first [`MAX_TAGS`] whose name and value are at most /// [`MAX_TAG_TEXT`] bytes. → whether any was dropped. diff --git a/crates/engine/src/tests/script_tags.rs b/crates/engine/src/tests/script_tags.rs index 79acc49546..5fc00f0cb0 100644 --- a/crates/engine/src/tests/script_tags.rs +++ b/crates/engine/src/tests/script_tags.rs @@ -260,3 +260,26 @@ fn tags_survive_native_save_and_open_and_hostile_ones_are_trimmed() { ids.dedup(); assert_eq!(ids.len(), MAX_TAGS); } + +#[test] +fn a_file_with_a_tag_id_that_is_not_a_whole_number_opens_and_the_tag_gets_a_new_id() { + let (s, a, _) = doc(); + let mut doc = (*s.active().unwrap().doc).clone(); + doc.node_mut(a).unwrap().edit_attrs(|at| { + at.tags = + ["k0", "k1", "k2"].iter().enumerate().map(|(i, n)| ObjectTag { id: 424_240 + i as u64, name: (*n).into(), value: "v".into() }).collect(); + }); + let mut hostile = String::from_utf8(vectorcraft_format::save(&doc, false)).unwrap(); + for (from, to) in [("\"id\":424240", "\"id\":-1"), ("\"id\":424241", "\"id\":1.5"), ("\"id\":424242", "\"id\":\"x\"")] { + assert!(hostile.contains(from), "{from}"); + hostile = hostile.replace(from, to); + } + let back = vectorcraft_format::load(hostile.as_bytes()).unwrap(); + let t = crate::cmd::tags::tags_of(back.node(a).unwrap()); + assert_eq!(t.iter().map(|t| (t.name.as_str(), t.value.as_str())).collect::>(), [("k0", "v"), ("k1", "v"), ("k2", "v")]); + let mut ids: Vec = t.iter().map(|t| t.id).collect(); + assert!(ids.iter().all(|id| *id >= 1 && *id < back.peek_next_id()), "{ids:?}"); + ids.sort_unstable(); + ids.dedup(); + assert_eq!(ids.len(), 3); +} diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index f599f71a37..5c0940e27a 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1032,7 +1032,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - The control server writes each reply through a 64 KiB buffer. On Windows 11 it sends the 17 MB `document.inspect` reply of a document with 50,000 objects on one layer to a client over loopback in 0.09 s instead of 34 s. - Scripts: File › Scripts › Other Script… and `script.run` run a JavaScript file against the open documents as one transaction with one undo step for each changed document. A failed or stopped run puts every document back. `crates/engine/src/tests/script_run.rs`. - Scripts: the global `app` gives the open documents, new documents from a startup preset and a `DocumentPreset`, the active document, each document's selection and its page items with their names, notes, visibility, lock, opacity, position, size, bounds and stacking order, and moves and copies them into or beside other objects, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/Application/, https://ai-scripting.docsforadobe.dev/jsobjref/Documents/, https://ai-scripting.docsforadobe.dev/jsobjref/DocumentPreset/, https://ai-scripting.docsforadobe.dev/jsobjref/Document/, https://ai-scripting.docsforadobe.dev/jsobjref/PageItems/, https://ai-scripting.docsforadobe.dev/jsobjref/PageItem/ and https://ai-scripting.docsforadobe.dev/jsobjref/GroupItem/ describe them; each change runs a command inside the run's transaction (`docs/mcp.md`). Layers, paths, type and the other classes are not there yet. `crates/engine/src/tests/script_dom.rs`. - - Scripts: `PageItem.tags` and `Document.tags` read, add, rename and delete an object's tags, name and value pairs that the native file keeps, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/Tags/ and https://ai-scripting.docsforadobe.dev/jsobjref/Tag/ describe them, through `object.tags` and the `object.tag.*` commands, at most 64 tags an object (`docs/mcp.md`). `crates/engine/src/tests/script_tags.rs`. + - Scripts: `PageItem.tags` reads, adds, renames and deletes an object's tags, name and value pairs that the native file keeps, and `Document.tags` reads, renames and deletes the tags of every page item but adds none (its `add` throws; a script adds a tag through the page item's `tags`), as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/Tags/ and https://ai-scripting.docsforadobe.dev/jsobjref/Tag/ describe them, through `object.tags` and the `object.tag.*` commands, at most 64 tags an object (`docs/mcp.md`). `crates/engine/src/tests/script_tags.rs`. - Scripts: 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 31afa8a523d5b4cf13a8bff59251fc7ab8d70adc Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 25 Nov 2026 05:33:16 -0800 Subject: [PATCH 077/151] Save for Web: docs describe the color table commands without dialog menu entries The Save for Web dialog's color table menu does not list Save Color Table or Load Color Table yet; both run through the engine and MCP. --- docs/mcp.md | 10 ++++------ docs/target-app-parity.md | 2 +- 2 files changed, 5 insertions(+), 7 deletions(-) diff --git a/docs/mcp.md b/docs/mcp.md index ca86c160c9..c62612479a 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -10955,7 +10955,7 @@ are written as lowercase `#rrggbb`. A `#rrggbbaa` spelling names no table color. right, with the lock mark, and Lock stays on until the color is unshifted. Web Shift replaces a shift by hand, and Unshift All Colors in the table's menu clears `shifted` and `webShift`. Only Web Colors in the picker starts off. -Save Color Table… in the table's menu is `document.exportForWeb.saveColorTable {path?, slice?, …settings}`. It writes +Save Color Table is `document.exportForWeb.saveColorTable {path?, slice?, …settings}`. It writes the GIF or PNG-8 color table the preview shows as a color table file (`.act`) in the layout the file format specification gives (https://www.adobe.com/devnet-apps/photoshop/fileformatashtml/): 256 entries of three bytes (red, green, blue) in file order, with zero bytes after the colors used, then the number of colors used and the index of the @@ -10965,7 +10965,7 @@ the file holds the whole image's table, also when `slices` is `selected` and no up among the slices `slices` names. `.act` is added to a `path` without an extension, and without `path` the file comes back as `dataBase64`. The reply is `{path, colors, transparentIndex, bytes, warnings}` (`transparentIndex` is null when there is none). JPEG and PNG-24 are errors, and the -document and the settings do not change. Load Color Table… is `webExport.loadColorTable {path | dataBase64, +document and the settings do not change. Load Color Table is `webExport.loadColorTable {path | dataBase64, …settings}`. It reads a 768-byte file (256 colors, no transparent entry) or a 772-byte one (the number of colors used, 1 to 256, and the transparent entry's index; an index past the colors used names no entry) and returns `{colors, transparentIndex, settings}`: the settings with the file's colors other than its transparent entry as @@ -10974,10 +10974,8 @@ document and the settings do not change. Load Color Table… is `webExport.loadC color is written as it is, in the file's order, and none is locked. A file whose only color is its transparent entry loads that color. Another file size (base64 text included), a count of 0 or above 256, both or neither of `path` and `dataBase64`, and JPEG or PNG-24 are errors; the command reads at most 773 bytes of a file and -remembers nothing. In -the dialog Load Color Table… puts the loaded settings into its fields (`__loadColorTable: true`), and Save Color Table… -writes the file picked in a save panel (`__saveColorTable: true`), or downloads it on the web, where Load Color Table… -is disabled. The help page describes both entries +remembers nothing. The Save for Web dialog's color table menu does not list Save Color Table… or Load Color +Table… yet; both commands run through the engine and MCP. The help page describes both entries (https://help.adobe.com/archive/en_US/illustrator/cs4/illustrator_cs4_help.pdf#page=404). ```json diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index cdeae6c612..746b1aa1ac 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1015,7 +1015,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - Save for Web: while Alt (Option on macOS) is held, the dialog's Cancel button reads Reset, which puts the remembered settings back on the document's active artboard and leaves the dialog open (`ui.dialogReset`). - Save for Web: the color table's trash button and Delete Color in its menu remove the selected GIF or PNG-8 colors, and their pixels take the nearest color left in the palette ([the help page](https://help.adobe.com/archive/en_US/illustrator/cs4/illustrator_cs4_help.pdf#page=404)). Click selects one color, Shift-click a range and Ctrl-click (Command-click on macOS) adds or removes one ([the help page](https://help.adobe.com/archive/en_US/illustrator/cs3/illustrator_cs3_help.pdf#page=398)). After the first deletion the table is a fixed Custom palette, so deleted colors stay out when the preview updates. These rules are VectorCraft's own: a deleted color is no longer locked, transparent or web-shifted; deleting every opaque color is refused; Restore Generated Table in the menu, or another reduction, goes back to the generated palette; presets and the remembered settings keep the edit (`colorTable.deleted`, `colorTable.customPalette`). Fixed palettes can also use all 256 entries when nothing is transparent. Scores and estimates are unchanged. - Save for Web: double-clicking a GIF or PNG-8 color-table swatch opens the Color Picker, and its OK changes that color to the one picked everywhere it appears in the image. The swatch then shows the original color in its upper-left half and the new one in its lower-right half, with the lock mark, and the color stays through a lower color count. Double-clicking a changed swatch opens the picker on the original color, and OK on it changes the color back; Unshift All Colors in the table's menu undoes every change, web shifts included ([the help page](https://help.adobe.com/archive/en_US/illustrator/cs3/illustrator_cs3_help.pdf#page=398)). These rules are VectorCraft's own: Cancel changes nothing; a changed color wins over Web Shift, Web Snap and Lock, and pressing Web Shift replaces it; a color mapped to transparent stays transparent; two colors may change to the same color; a changed color takes a kept palette slot before a locked one, and one slot always stays for the reduction; the change is kept by source color when the reduction changes and applies only while that source is in the table; presets and the remembered settings keep it; the picker opens with Only Web Colors off (`colorTable.shifted`). GIF lossy compression moves no pixel into or out of a changed color. Scores and estimates are unchanged. - - Save for Web: Save Color Table… in the color table's menu writes the GIF or PNG-8 table the preview shows to an `.act` file, and Load Color Table… reads one back as the table's fixed Custom palette, so the image is written with the loaded colors; reloaded colors come back as plain, unlocked entries ([the help page](https://help.adobe.com/archive/en_US/illustrator/cs4/illustrator_cs4_help.pdf#page=404)). The file follows the published color table layout (https://www.adobe.com/devnet-apps/photoshop/fileformatashtml/): 256 RGB entries in file order, then the number of colors and the transparent entry. These rules are VectorCraft's own: Save always writes the 772-byte form, with zero bytes after the colors used and 65535 when there is no transparent entry; Load takes the 768-byte and 772-byte forms, leaves the transparent entry out of the palette, sets Colors to the file's count, clears the table's other edits and its sort, and sets Web Snap to 0; Load reads only `.act` files and is disabled on the web (`document.exportForWeb.saveColorTable`, `webExport.loadColorTable`). Scores and estimates are unchanged. + - Save for Web: the Save Color Table command writes the GIF or PNG-8 table the preview shows to an `.act` file, and the Load Color Table command reads one back as the table's fixed Custom palette, so the image is written with the loaded colors; reloaded colors come back as plain, unlocked entries ([the help page](https://help.adobe.com/archive/en_US/illustrator/cs4/illustrator_cs4_help.pdf#page=404)). Both run through the engine and MCP; the dialog's color table menu does not list them yet. The file follows the published color table layout (https://www.adobe.com/devnet-apps/photoshop/fileformatashtml/): 256 RGB entries in file order, then the number of colors and the transparent entry. These rules are VectorCraft's own: Save always writes the 772-byte form, with zero bytes after the colors used and 65535 when there is no transparent entry; Load takes the 768-byte and 772-byte forms, leaves the transparent entry out of the palette, sets Colors to the file's count, clears the table's other edits and its sort, and sets Web Snap to 0 (`document.exportForWeb.saveColorTable`, `webExport.loadColorTable`). Scores and estimates are unchanged. - Export for Screens, Save for Web (slice images, and files named after the document's title) and the Libraries panel name files with the characters Windows does not allow written as `-` and with a `-` after a Windows device name such as `CON`, on every platform (`document.exportForScreens`, `document.exportForWeb`, `library.create`). - Variables (data merge): text, visibility and image variables bound to objects (an object may carry several), dataset rows applied in one undo step (`variable.*`, `dataset.*`) from a Variables panel and Window › Variables, with dialogs to define, bind and edit, Make Text/Visibility/Image Dynamic, Capture/Update Data Set, CSV import/export (`dataset.import` / `dataset.export`), and a row in italics when an edit leaves the art not matching it; an image dataset value is a file path and apply keeps the object's bounds; bindings let go of deleted art and locked art is left alone except by visibility values; every command, like the rest, is drivable over MCP and the CLI. - Export for Screens numbers distinct row files whose names collide, compared without case, as `-2`, `-3`… instead of leaving them out; identical rows still write one file. It puts row folders that differ only in case into one folder (`document.exportForScreens`). From b21ff4503993d399040b549a1e884bf64dc051da Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 25 Nov 2026 08:51:11 -0800 Subject: [PATCH 078/151] Properties: test that the Profile row follows a selection change The row hides when the stroke with a variable width leaves the selection and shows again when it comes back, with the document unchanged. --- crates/ui-egui/src/panels/properties/tests.rs | 21 +++++++++++++++++++ 1 file changed, 21 insertions(+) diff --git a/crates/ui-egui/src/panels/properties/tests.rs b/crates/ui-egui/src/panels/properties/tests.rs index 2aa62025a4..26957d6388 100644 --- a/crates/ui-egui/src/panels/properties/tests.rs +++ b/crates/ui-egui/src/panels/properties/tests.rs @@ -1042,6 +1042,27 @@ fn the_width_profile_shows_while_another_selected_stroke_has_a_variable_width() } } +/// The Width Profile row follows a change of selection that leaves the document as it was: it +/// hides when the stroke with a variable width leaves the selection and shows again when it comes +/// back. +#[test] +fn the_width_profile_row_follows_a_selection_change() { + let mut app = new_app(); + let a = app.run("shape.line", json!({"x1": 20, "y1": 100, "x2": 300, "y2": 100})).unwrap()["id"].clone(); + let b = app.run("shape.line", json!({"x1": 20, "y1": 160, "x2": 300, "y2": 160})).unwrap()["id"].clone(); + app.run("select.set", json!({"ids": [b]})).unwrap(); + app.run("stroke.set", json!({"profile": "lens"})).unwrap(); + app.run("select.set", json!({"ids": [a, b]})).unwrap(); + let mut panel = Panel::new(app, show); + assert!(panel.shows("Profile"), "the other stroke has a variable width"); + panel.app().run("select.set", json!({"ids": [a]})).unwrap(); + panel.frame(); + assert!(!panel.shows("Profile"), "the uniform stroke alone"); + panel.app().run("select.set", json!({"ids": [a, b]})).unwrap(); + panel.frame(); + assert!(panel.shows("Profile"), "both strokes again"); +} + /// With Direct Selection, a path whose corner is selected shows that corner's kind and radius; /// each edit sets that corner alone in one undo step. Not with the Selection tool, nor with the /// whole path selected; a live rectangle keeps its own Corner Radius row instead. From a7cb77948ac9a7f14db63f96d695578d1b312a5f Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 25 Nov 2026 09:13:14 -0800 Subject: [PATCH 079/151] Save for Web: Save Color Table refuses an empty path An empty or blank `path` was treated as no path, so the command returned `dataBase64` and wrote no file. It is now an error, and a `path` left out still returns the file as `dataBase64`. --- crates/engine/src/cmd/webexport.rs | 10 ++++++---- crates/engine/src/tests/webexport.rs | 2 ++ docs/mcp.md | 3 ++- 3 files changed, 10 insertions(+), 5 deletions(-) diff --git a/crates/engine/src/cmd/webexport.rs b/crates/engine/src/cmd/webexport.rs index 18c24d98d1..d1ea281e68 100644 --- a/crates/engine/src/cmd/webexport.rs +++ b/crates/engine/src/cmd/webexport.rs @@ -50,7 +50,7 @@ pub fn specs() -> Vec { "Save Color Table", [], None, - "{path?: the .act file (.act is added to a name without an extension), …the settings of document.exportForWeb (preset?, format?: gif|png8…), slice?: n (1-based, from slice.list, among the slices `slices` names; default the whole image, whatever `slices` is)} write the GIF or PNG-8 color table the preview shows as a color table file: 772 bytes, the colors as written (red, green, blue) in file order, zero bytes up to 256 colors, then the number of colors and the transparent entry's index (65535 for none), two bytes each, most significant byte first → {path, colors (how many), transparentIndex (null for none), bytes, warnings}; no path → {dataBase64, colors, transparentIndex, bytes, warnings}. jpg and png24 are an error; the document and the settings do not change", + "{path?: the .act file (.act is added to a name without an extension), …the settings of document.exportForWeb (preset?, format?: gif|png8…), slice?: n (1-based, from slice.list, among the slices `slices` names; default the whole image, whatever `slices` is)} write the GIF or PNG-8 color table the preview shows as a color table file: 772 bytes, the colors as written (red, green, blue) in file order, zero bytes up to 256 colors, then the number of colors and the transparent entry's index (65535 for none), two bytes each, most significant byte first → {path, colors (how many), transparentIndex (null for none), bytes, warnings}; no path → {dataBase64, colors, transparentIndex, bytes, warnings}. An empty path, jpg and png24 are an error; the document and the settings do not change", has_doc, save_color_table ), @@ -1419,9 +1419,11 @@ fn save_color_table(s: &mut Session, p: &Value) -> Result { if !settings.format.palette() { return Err(no_table(P, settings.format)); } - let path = text_param(p, "path", P)? - .filter(|p| !p.trim().is_empty()) - .map(|p| if std::path::Path::new(p).extension().is_none() { format!("{p}.{COLOR_TABLE_EXT}") } else { p.to_string() }); + let path = text_param(p, "path", P)?; + if path.is_some_and(|p| p.trim().is_empty()) { + return Err(bad(P, "`path` is empty: give a file path, or leave it out for `dataBase64`")); + } + let path = path.map(|p| if std::path::Path::new(p).extension().is_none() { format!("{p}.{COLOR_TABLE_EXT}") } else { p.to_string() }); let Shown { o, warnings, .. } = shown(s, &settings, p, P, false)?; let bytes = act_bytes(&o.colors); let mut out = json!({ diff --git a/crates/engine/src/tests/webexport.rs b/crates/engine/src/tests/webexport.rs index 5eb55d03c2..b95dccfd23 100644 --- a/crates/engine/src/tests/webexport.rs +++ b/crates/engine/src/tests/webexport.rs @@ -1137,6 +1137,8 @@ fn save_color_table_writes_the_path_and_refuses_bad_params() { (json!({"format": "jpg"}), "`jpg` has no color table"), (json!({"format": "png24"}), "`png24` has no color table"), (json!({"path": 5}), "`path` must be a string"), + (json!({"path": ""}), "`path` is empty"), + (json!({"path": " "}), "`path` is empty"), (json!({"slice": "1"}), "`slice` is a slice number"), (json!({"slice": 0}), "`slice` is a slice number"), ] { diff --git a/docs/mcp.md b/docs/mcp.md index c62612479a..bb53f197eb 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -10964,7 +10964,8 @@ transparent entry, two bytes each with the most significant byte first. The file the file holds the whole image's table, also when `slices` is `selected` and no slice is selected; a `slice` is looked up among the slices `slices` names. `.act` is added to a `path` without an extension, and without `path` the file comes back as `dataBase64`. The reply is `{path, colors, -transparentIndex, bytes, warnings}` (`transparentIndex` is null when there is none). JPEG and PNG-24 are errors, and the +transparentIndex, bytes, warnings}` (`transparentIndex` is null when there is none). An empty `path`, JPEG and PNG-24 +are errors, and the document and the settings do not change. Load Color Table is `webExport.loadColorTable {path | dataBase64, …settings}`. It reads a 768-byte file (256 colors, no transparent entry) or a 772-byte one (the number of colors used, 1 to 256, and the transparent entry's index; an index past the colors used names no entry) and returns From 1e8b2fcb321b7f63d3e61025f675ce75cc429836 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 25 Nov 2026 09:17:37 -0800 Subject: [PATCH 080/151] Gradient panel: a picked midpoint and a selected stop stay selected when the document tab moves The owner a selected stop, freeform point or midpoint diamond is kept for now records the active document's uid instead of its tab index. Dragging the document's tab along the strip (document.move) changed the index, so the selection was dropped and the Location field was disabled although the gradient had not changed. --- crates/engine/src/cmd/gradient.rs | 5 +++-- crates/ui-egui/src/panels/gradient/tests.rs | 22 +++++++++++++++++++++ 2 files changed, 25 insertions(+), 2 deletions(-) diff --git a/crates/engine/src/cmd/gradient.rs b/crates/engine/src/cmd/gradient.rs index 3bc72bc816..12d6fb69c8 100644 --- a/crates/engine/src/cmd/gradient.rs +++ b/crates/engine/src/cmd/gradient.rs @@ -91,7 +91,8 @@ fn select_stop(s: &mut Session, p: &Value) -> Result { /// ([`Session::gradient_owner`]). #[derive(Clone, Copy, Debug, PartialEq)] pub struct StopOwner { - doc: Option, + /// The active document's uid, which stays the same when its tab moves. + doc: Option, object: Option, /// The object whose paint the active proxy shows: a Live Paint group without faces (or edges) /// first in the selection shows the next object's. @@ -106,7 +107,7 @@ impl StopOwner { pub(crate) fn of(s: &Session) -> Self { let st = s.active(); Self { - doc: s.active, + doc: st.map(|d| d.uid), object: st.and_then(|d| d.selection.objects.first().copied()), source: s.proxy_source(!s.fill_active).map(|(n, _)| n.id), part: st.is_some_and(|d| d.selection.symbol_part.is_some()), diff --git a/crates/ui-egui/src/panels/gradient/tests.rs b/crates/ui-egui/src/panels/gradient/tests.rs index 9efa27a97f..e874fbee5d 100644 --- a/crates/ui-egui/src/panels/gradient/tests.rs +++ b/crates/ui-egui/src/panels/gradient/tests.rs @@ -205,6 +205,28 @@ fn a_picked_diamond_stays_with_the_gradient_it_was_picked_on() { assert_eq!(mid(&rig), None, "the object's stroke"); } +/// Dragging the document's tab along the strip keeps its selected stop and its picked diamond +/// selected: both stay with the document, not with the tab it was in. +#[test] +fn a_selected_stop_and_a_picked_diamond_stay_selected_when_the_document_tab_moves() { + let stops = json!([{"offset": 0, "color": "#ffffff", "midpoint": 0.3}, {"offset": 1, "color": "#000000"}]); + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 300, "height": 300})).unwrap(); + app.run("file.new", json!({"width": 300, "height": 300})).unwrap(); + app.run("shape.rectangle", json!({"x": 100, "y": 100, "width": 100, "height": 100})).unwrap(); + app.run("paint.setFill", json!({"gradient": {"stops": stops}})).unwrap(); + app.run("gradient.selectStop", json!({"index": 1})).unwrap(); + app.run("document.move", json!({"to": 0})).unwrap(); + assert_eq!(app.session.selected_stop(), Some(1), "the stop stays selected in the moved tab"); + let mut rig = Rig::new(app); + rig.click("Midpoint 1"); + assert_eq!(selected_mid(&rig.app(), 2), Some(0), "the diamond is picked"); + rig.app().run("document.move", json!({"to": 1})).unwrap(); + rig.fixture.settle(); + assert_eq!(selected_mid(&rig.app(), 2), Some(0), "the diamond stays picked in the moved tab"); + assert_eq!(rig.number("Location"), Some(30.0), "Location still shows the midpoint"); +} + /// A mirrored conic's Aspect Ratio field shows the extent's size, and a typed value keeps the /// sweep mirrored (the field's value times the mirror's sign). #[test] From 73978a194fc3402afa123d28b68565a6eec746ad Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 25 Nov 2026 10:00:05 -0800 Subject: [PATCH 081/151] Scripts: script.grants.revoke matches a path as given as well as resolved A grant whose path a link has since replaced is listed by script.grants under the path it was kept for, but script.grants.revoke followed the link and compared the link's target, so Revoke in Script File Access removed nothing. A path is now matched as given and, inside the automation read roots, also with its links followed. --- crates/engine/src/cmd/scripts.rs | 17 ++++++++++------- crates/engine/src/script/files.rs | 10 +++++----- crates/engine/src/tests/script_io.rs | 22 ++++++++++++++++++++++ docs/mcp.md | 2 +- 4 files changed, 38 insertions(+), 13 deletions(-) diff --git a/crates/engine/src/cmd/scripts.rs b/crates/engine/src/cmd/scripts.rs index 2640433606..14ad0685fd 100644 --- a/crates/engine/src/cmd/scripts.rs +++ b/crates/engine/src/cmd/scripts.rs @@ -104,7 +104,7 @@ pub fn specs() -> Vec { "Revoke Script File Permissions", [], None, - "{script?: a script file's path, path?: an allowed file or folder's path, all?: true (exactly one of all and the other two)} remove the kept file access of that script, of that path, of both together, or every one; a path is matched as script.grants lists it, after its links are followed (a path outside the automation read roots is matched as given); refused with the busy error while a script runs, as the run keeps the grants it started with → {removed: how many}", + "{script?: a script file's path, path?: an allowed file or folder's path, all?: true (exactly one of all and the other two)} remove the kept file access of that script, of that path, of both together, or every one; a path is matched as given and as script.grants lists it, after its links are followed (a path outside the automation read roots is matched as given only); refused with the busy error while a script runs, as the run keeps the grants it started with → {removed: how many}", always, grants_revoke ), @@ -384,16 +384,19 @@ fn grants(s: &mut Session, _: &Value) -> Result { fn grants_revoke(s: &mut Session, p: &Value) -> Result { const C: &str = "script.grants.revoke"; + // A path is matched as given, and also with its links followed, so a grant whose path a link + // has since taken the place of is still removed. A path the request may not read (outside the + // automation read roots, a network path among them) is compared as written, without looking it up. let path_of = |key: &str| match p.get(key) { None => Ok(None), - // A path the request may not read (outside the automation read roots, a network path among - // them) is compared as written, without looking it up. - Some(Value::String(t)) if !t.is_empty() => Ok(Some( - crate::file_access::check_read(t) + Some(Value::String(t)) if !t.is_empty() => { + let real = crate::file_access::check_read(t) .ok() .and_then(|()| std::fs::canonicalize(t).ok()) - .map_or_else(|| t.clone(), |real| crate::cmd::findfiles::plain(real).to_string_lossy().into_owned()), - )), + .map(|real| crate::cmd::findfiles::plain(real).to_string_lossy().into_owned()) + .filter(|real| real != t); + Ok(Some([Some(t.clone()), real].into_iter().flatten().collect::>())) + } Some(_) => Err(bad(C, format!("`{key}` must be a path"))), }; let (script_path, path) = (path_of("script")?, path_of("path")?); diff --git a/crates/engine/src/script/files.rs b/crates/engine/src/script/files.rs index 476fbde5ad..a914f2d474 100644 --- a/crates/engine/src/script/files.rs +++ b/crates/engine/src/script/files.rs @@ -1079,15 +1079,15 @@ pub(crate) fn stored_grants(data_dir: &Path) -> std::io::Result, path: Option<&str>) -> std::io::Result { +/// `path` (each matched by any of its spellings), of both when both are given and of every grant +/// when neither is (`script.grants.revoke`). → how many were removed. +pub(crate) fn revoke_grants(data_dir: &Path, script: Option<&[String]>, path: Option<&[String]>) -> std::io::Result { let store = data_dir.with_file_name(GRANTS_FILE); let _lock = lock_store(&store)?; let grants = try_read_store(&store)?; let before = grants.len(); - let kept: Vec = - grants.into_iter().filter(|g| !(script.is_none_or(|s| g["script"] == *s) && path.is_none_or(|p| g["path"] == *p))).collect(); + let matches = |value: &serde_json::Value, names: Option<&[String]>| names.is_none_or(|names| names.iter().any(|n| value == n.as_str())); + let kept: Vec = grants.into_iter().filter(|g| !(matches(&g["script"], script) && matches(&g["path"], path))).collect(); let removed = before - kept.len(); if removed > 0 { write_store(&store, kept)?; diff --git a/crates/engine/src/tests/script_io.rs b/crates/engine/src/tests/script_io.rs index e5d854850d..d4eed1b4f4 100644 --- a/crates/engine/src/tests/script_io.rs +++ b/crates/engine/src/tests/script_io.rs @@ -652,6 +652,28 @@ fn a_grants_change_without_its_lock_changes_nothing() { let _ = std::fs::remove_dir_all(base); } +/// `script.grants.revoke` removes a grant by the path `script.grants` lists for it, also when a +/// link has since taken that path's place and leads elsewhere. +#[cfg(unix)] +#[test] +fn a_grant_whose_path_is_now_a_link_is_revoked_by_its_listed_path() { + let base = folder("grants-relinked"); + let real = std::fs::canonicalize(&base).unwrap(); + let (kept, other) = (real.join("kept.txt"), real.join("other.txt")); + write(&other, b"other"); + let kept_path = kept.to_string_lossy().into_owned(); + let grant = json!({"script": "/s.jsx", "sha256": "0", "code": [], "path": kept_path, "write": false, "folder": false}); + write(&base.join("settings/Script Grants.json"), json!({"version": 1, "grants": [grant]}).to_string().as_bytes()); + std::os::unix::fs::symlink(&other, &kept).unwrap(); + let mut s = with_data(&base); + let listed = s.execute("script.grants", &json!({})).unwrap(); + assert_eq!(listed["grants"][0]["path"], json!(kept_path)); + let r = s.execute("script.grants.revoke", &json!({"script": "/s.jsx", "path": kept_path})).unwrap(); + assert_eq!(r["removed"], 1, "{r}"); + assert_eq!(s.execute("script.grants", &json!({})).unwrap()["grants"], json!([])); + let _ = std::fs::remove_dir_all(base); +} + /// Reading and changing the grants file wait for a lock another handle holds only for a bounded /// number of tries: then a listing and a change fail, with the file unchanged. A lock /// released while it waits is taken. diff --git a/docs/mcp.md b/docs/mcp.md index 0b7369d02e..6518d6868e 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -3132,7 +3132,7 @@ takes its place), and `file` the grants file's path, or `null` without a settings folder. Under automation read roots, a `script`, `path` or `file` outside them is given as its file name alone. `script.grants.revoke {script?, path?, all?}` removes the grants of a script file, of a path, of both together, or with `all: true` every grant, and returns `{removed}`. A path is -matched after its links are followed; under automation read roots, a path outside them is matched as given. While a script +matched as given and after its links are followed; under automation read roots, a path outside them is matched as given only. While a script runs it is refused with the busy error, as the run keeps the grants it started with. A grants file that is there but cannot be read, a link to a missing file included, is left as it is: `script.grants` and `script.grants.revoke` fail, and a grant picked with Always is not kept. A missing grants file lists no grants, and `script.grants` leaves out a grant in the file that is not well From 6ce8c5fb5594e5c3d6bf93f14ee5b16ac0aed772 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 25 Nov 2026 13:40:48 -0800 Subject: [PATCH 082/151] Variables: a click on the highlighted variable selects its bound object again The Variables table ran the row click only when the table's selection changed. A click on the row that is already highlighted leaves that selection as it was, so after the art was deselected on the canvas, a second click on the same variable selected nothing. The table now also runs the row click on the collection's Picked event, which reports a click that leaves the selection unchanged. --- crates/ui-egui/src/panels/variables.rs | 29 ++++++++++++++++++++++++++ 1 file changed, 29 insertions(+) diff --git a/crates/ui-egui/src/panels/variables.rs b/crates/ui-egui/src/panels/variables.rs index 3ff0fd0191..257d986eb2 100644 --- a/crates/ui-egui/src/panels/variables.rs +++ b/crates/ui-egui/src/panels/variables.rs @@ -522,6 +522,8 @@ fn variable_table(ui: &mut Ui, vars: &[VarRow], sort: VariableSort, states: &Row } } CollectionEvent::Selection { change: SelectionChange::Set(keys), .. } => acts.extend(keys.into_iter().next().map(Act::Click)), + // A click on the highlighted row changes no selection, and still selects what it drives. + CollectionEvent::Picked { key, .. } => acts.push(Act::Click(key)), CollectionEvent::Activate(name) if !states.locked => acts.push(Act::Options(name)), _ => {} } @@ -956,6 +958,33 @@ mod tests { assert_eq!(sets["datasets"][0]["name"], "Data Set 2"); } + /// A click on the highlighted row selects what it drives again, as a click on any other row + /// does: after the art is deselected on the canvas, the row stays highlighted, and a second + /// click on it selects the bound object. + #[test] + fn a_click_on_the_highlighted_row_selects_its_bound_object_again() { + use egui::accesskit::Role; + let mut app = app_with_data(); + let bound = app.session.doc().unwrap().doc.variables.objects_of("Name")[0]; + let mut d = Driver::new(); + let row = |d: &mut Driver, app: &mut VectorcraftApp| { + let nodes = d.nodes(app); + nodes.iter().find(|(_, n)| n.role() != Role::ColumnHeader && n.label() == Some("Name")).expect("the Name row").1.clone() + }; + let selected = |app: &VectorcraftApp| app.session.doc().unwrap().selection.objects.clone(); + app.session.execute("select.set", &json!({"ids": []})).unwrap(); + let cell = row(&mut d, &mut app); + d.click(&mut app, &cell); + assert_eq!(highlighted_row(app.session.doc().unwrap()).as_deref(), Some("Name")); + assert_eq!(selected(&app), vec![bound], "the first click selects the bound object"); + app.session.execute("select.set", &json!({"ids": []})).unwrap(); + assert!(selected(&app).is_empty()); + let cell = row(&mut d, &mut app); + d.click(&mut app, &cell); + assert_eq!(highlighted_row(app.session.doc().unwrap()).as_deref(), Some("Name")); + assert_eq!(selected(&app), vec![bound], "a click on the highlighted row selects the bound object again"); + } + /// The rows as the panel built them on every frame before [`cached_rows`] kept them: the /// identity checks compare against it. fn old_rows(st: &DocState, xml_id: bool) -> Rows { From c0487189bd3bf4ff898e02eaef190b48898527f2 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 25 Nov 2026 13:49:06 -0800 Subject: [PATCH 083/151] Scripts: check then's parameters and keep a failed startup script's message script.startup.run checks then's parameters as script.run checks them, before any startup script runs. In the app, the message of a startup script that fails or is stopped, through the quit prompt too, stays in the status bar's notes after the chosen script ends. --- crates/engine/src/cmd/scripts.rs | 12 ++++++++++-- crates/engine/tests/script_startup.rs | 7 +++++++ crates/ui-egui/src/dialogs/script_run.rs | 3 ++- crates/ui-egui/src/script_runs.rs | 13 ++++++++++++- crates/ui-egui/src/tests/script_run.rs | 21 +++++++++++++++++++++ crates/ui-egui/src/tests/scripts_menu.rs | 7 +++++-- docs/mcp.md | 5 +++-- 7 files changed, 60 insertions(+), 8 deletions(-) diff --git a/crates/engine/src/cmd/scripts.rs b/crates/engine/src/cmd/scripts.rs index 71a99a25b2..8cec1db4f6 100644 --- a/crates/engine/src/cmd/scripts.rs +++ b/crates/engine/src/cmd/scripts.rs @@ -95,7 +95,7 @@ pub fn specs() -> Vec { "Run Startup Scripts", [], None, - "{reason: launch|menu (launch: the app starting; menu: before a script chosen from File › Scripts), then?: script.run's parameters (the script to run once the startup scripts have run), maxFuel?: whole number from 1 to 100000000000 (each startup script's instructions; default 1000000000)} run the .jsx files of the Startup Scripts folder next to the settings, one at a time, as script.run runs a file, each with the same limits as any script and its own undo step; nothing runs, and the reply says why, when the runStartupScripts preference is off (the default), in Safe Mode, or in a session without the folder (the web, and a run with VECTORCRAFT_NO_PREFS); only the folder's own .jsx files run, sorted by name without regard to case, then by name; links, hidden files, names starting with a dot, subfolders and other files are left out, and so is a script the Safe Mode choice disabled; a missing folder runs nothing; a script that cannot be read, is larger than 8 MiB, fails or is stopped is named in failed and in the Script Console, and the next one runs, then the script of then; while a startup script runs, the launch marker names it, so a launch that stops there offers to disable it; script.* commands are refused inside a script, so a startup script does not start another startup run. VectorCraft's own rules: the folder, the order, the limits of a listing (2048 folder entries, 512 scripts, 250 ms) and what a failure does → {reason, skipped: true, why: off|safeMode|noFolder, then?: script.run's reply} | {reason, skipped: false, ran: [names], failed: [{name, error}], disabled: [names], truncated, unreadable, then?: script.run's reply}, or, in the app, {reason, skipped: false, running, queued: the runs queued, then's included, failed: [{name, error}] (the runs that could not start before the first one did), disabled, truncated, unreadable, then?: script.run's reply when it ran to its end at once}, each run then reporting as script.run's do, and a later run that cannot start is named in the status bar", + "{reason: launch|menu (launch: the app starting; menu: before a script chosen from File › Scripts), then?: script.run's parameters (the script to run once the startup scripts have run), maxFuel?: whole number from 1 to 100000000000 (each startup script's instructions; default 1000000000)} run the .jsx files of the Startup Scripts folder next to the settings, one at a time, as script.run runs a file, each with the same limits as any script and its own undo step; nothing runs, and the reply says why, when the runStartupScripts preference is off (the default), in Safe Mode, or in a session without the folder (the web, and a run with VECTORCRAFT_NO_PREFS); only the folder's own .jsx files run, sorted by name without regard to case, then by name; links, hidden files, names starting with a dot, subfolders and other files are left out, and so is a script the Safe Mode choice disabled; a missing folder runs nothing; a script that cannot be read, is larger than 8 MiB, fails or is stopped is named in failed and in the Script Console, and the next one runs, then the script of then; while a startup script runs, the launch marker names it, so a launch that stops there offers to disable it; script.* commands are refused inside a script, so a startup script does not start another startup run. VectorCraft's own rules: the folder, the order, the limits of a listing (2048 folder entries, 512 scripts, 250 ms) and what a failure does → {reason, skipped: true, why: off|safeMode|noFolder, then?: script.run's reply} | {reason, skipped: false, ran: [names], failed: [{name, error}], disabled: [names], truncated, unreadable, then?: script.run's reply}, or, in the app, {reason, skipped: false, running, queued: the runs queued, then's included, failed: [{name, error}] (the runs that could not start before the first one did), disabled, truncated, unreadable, then?: script.run's reply when it ran to its end at once}, each run then reporting as script.run's do, and a later run that cannot start is named in the status bar, where the message of a startup script that fails or is stopped also stays", always, startup_run ), @@ -394,6 +394,12 @@ impl Session { } } + /// The running script is a startup script (`script.startup.run`), not the script queued after + /// them. + pub fn startup_script_running(&self) -> bool { + self.startup_loading.is_some() + } + /// Begins a run of the startup script at `path`, read now and checked as `script.run` checks a /// file, with the launch marker naming it while it runs. → the run's name, or the error that kept /// it from starting, which the Script Console also shows. @@ -534,8 +540,10 @@ fn startup_run(s: &mut Session, p: &Value) -> Result { if s.script_running() { return Err(EngineError::Busy); } - // A chosen script that cannot start ends the request before any startup script runs. + // A chosen script that cannot start ends the request before any startup script runs, and its + // parameters are checked as `script.run` checks them. if let Some(then) = &then { + super::params::check_params("script.run", then)?; prepare(s, then)?; } let root = match (s.startup_skip(), s.startup_scripts_dir()) { diff --git a/crates/engine/tests/script_startup.rs b/crates/engine/tests/script_startup.rs index 99e29ecf14..f6ca150ded 100644 --- a/crates/engine/tests/script_startup.rs +++ b/crates/engine/tests/script_startup.rs @@ -217,6 +217,13 @@ fn bad_parameters_are_refused() { ] { assert!(s.execute("script.startup.run", &p).is_err(), "{p}"); } + // `then` is checked as `script.run` checks its parameters, before any startup script runs. + write(&dir, "a.jsx", "vc.log(1);"); + let then = json!({"source": "vc.log(2);", "bogus": true}); + let alone = s.execute("script.run", &then).unwrap_err().to_string(); + let e = s.execute("script.startup.run", &json!({"reason": "menu", "then": then})).unwrap_err().to_string(); + assert_eq!(e, alone); + assert!(started(&s).is_empty(), "no startup script ran"); } #[test] diff --git a/crates/ui-egui/src/dialogs/script_run.rs b/crates/ui-egui/src/dialogs/script_run.rs index 89164b63f2..f7f005d9fa 100644 --- a/crates/ui-egui/src/dialogs/script_run.rs +++ b/crates/ui-egui/src/dialogs/script_run.rs @@ -578,12 +578,13 @@ pub(crate) fn pump(app: &mut VectorcraftApp, _ctx: &egui::Context) { } None => {} } + let startup = app.session.startup_script_running(); if let Some(DialogResult::Ok(answer)) = close && answer.choice == PromptChoice::Proceed && app.session.script_abandon() { let error = app.session.script_failure_text().unwrap_or_default(); - crate::script_runs::failed(app, error); + crate::script_runs::ended_with_error(app, startup, error); forget::(app); forget::(app); app.sync_views(); diff --git a/crates/ui-egui/src/script_runs.rs b/crates/ui-egui/src/script_runs.rs index c2d4d78d46..5b5ffc099b 100644 --- a/crates/ui-egui/src/script_runs.rs +++ b/crates/ui-egui/src/script_runs.rs @@ -19,6 +19,7 @@ pub fn poll(app: &mut VectorcraftApp) { return; } let name = app.session.script_name().unwrap_or_default(); + let startup = app.session.startup_script_running(); let Some(result) = app.session.script_pump() else { // A pump that started the next queued run shows the runs before it that could not start // in this frame: with none left running, the app may draw no next one. @@ -36,7 +37,7 @@ pub fn poll(app: &mut VectorcraftApp) { app.status(format!("Ran {name}")); } } - Err(e) => failed(app, e.to_string()), + Err(e) => ended_with_error(app, startup, e.to_string()), } startup_failures(app); app.sync_views(); @@ -174,6 +175,16 @@ pub fn run_at_launch(app: &mut VectorcraftApp) { } } +/// Shows why a run ended without its changes ([`failed`]). When the run was a startup script +/// (`startup`), the message also stays in the round's notes, so the message of the run that ends +/// the round does not hide it ([`end_round`]). +pub(crate) fn ended_with_error(app: &mut VectorcraftApp, startup: bool, error: String) { + failed(app, error); + if startup { + app.ui.startup_notes.push(app.ui.status.clone()); + } +} + /// Shows why a run ended without its changes. A stopped run that wrote no file says only that it /// was stopped; any other failure shows its error, which names the files left written. pub(crate) fn failed(app: &mut VectorcraftApp, error: String) { diff --git a/crates/ui-egui/src/tests/script_run.rs b/crates/ui-egui/src/tests/script_run.rs index 4022cb7c65..f7e9a33f7b 100644 --- a/crates/ui-egui/src/tests/script_run.rs +++ b/crates/ui-egui/src/tests/script_run.rs @@ -257,6 +257,27 @@ fn quitting_asks_to_stop_and_stop_undoes_the_run() { assert_eq!(app.ui.status, "The script was stopped and its changes were undone"); } +#[test] +fn a_startup_script_stopped_by_quitting_stays_in_the_status_bar() { + let mut app = app(); + let dir = folder("startup-quit"); + std::fs::write(dir.join("a.jsx"), "for (;;) {}").unwrap(); + app.session.attach_startup_scripts_dir(dir.clone()); + app.session.prefs.show_external_script_warning = false; + app.run("prefs.set", json!({"key": "runStartupScripts", "value": true})).unwrap(); + menus::run_ui_command(&mut app, "ui.runScript", &json!({ "source": DRAW, "name": "chosen" })).unwrap().unwrap(); + script_runs::poll(&mut app); + assert!(app.session.startup_script_running()); + script_run::ask_to_close(&mut app); + assert!(confirm(&mut app, CLOSE_KIND)); + finish(&mut app); + script_runs::poll(&mut app); + let stopped = "The script was stopped and its changes were undone"; + assert_eq!(app.ui.status, stopped); + assert_eq!(app.ui.status_notes.as_ref().and_then(|(_, notes)| notes.first()).map(String::as_str), Some(stopped)); + let _ = std::fs::remove_dir_all(&dir); +} + #[test] fn a_stop_names_the_files_the_run_left_written() { let mut app = app(); diff --git a/crates/ui-egui/src/tests/scripts_menu.rs b/crates/ui-egui/src/tests/scripts_menu.rs index f6cc325f05..ce1dfdfae8 100644 --- a/crates/ui-egui/src/tests/scripts_menu.rs +++ b/crates/ui-egui/src/tests/scripts_menu.rs @@ -545,10 +545,13 @@ fn a_stopped_startup_script_says_it_was_stopped_and_the_chosen_script_still_runs } script_runs::poll(&mut app); } - assert_eq!(app.ui.status, "The script was stopped and its changes were undone"); + let stopped = "The script was stopped and its changes were undone".to_string(); + assert_eq!(app.ui.status, stopped); finish(&mut app); assert_eq!(started(&app), ["a.jsx", "chosen"]); - assert_eq!(app.ui.status, "Ran chosen"); + // The stopped startup script stays in sight when the chosen script ends, with its message in the hover. + assert_eq!(app.ui.status, stopped); + assert_eq!(app.ui.status_notes, Some((stopped.clone(), vec![stopped, "Ran chosen".to_string()]))); let _ = std::fs::remove_dir_all(dir); } diff --git a/docs/mcp.md b/docs/mcp.md index 8f6a64c800..3cac78f102 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -3278,8 +3278,9 @@ The rest of this section is VectorCraft's own rules: entry it cannot read, the status bar says that the folder was not read in full. A folder that is missing runs nothing. At launch and before a chosen script, when the folder is there and cannot be read, or a file is where the folder should be, the status bar says that the folder cannot be read. -- These two notes, and the names of startup scripts that could not start, stay in the status bar after the last run - ends: the status bar shows the first of them, and its hover lists them all, then the last run's message. +- These two notes, the names of startup scripts that could not start, and the message of each startup script that + failed or was stopped stay in the status bar after the last run ends: the status bar shows the first of them, and + its hover lists them all, then the last run's message. - The scripts run one at a time, sorted by name without regard to case, then by name. Each runs as `script.run` runs a file, with the same limits, and each that changes a document adds its own Run Script undo step. The chosen script runs after the last of them. From c29eb5e6e4416053c13ae08b0fc57f92536c5d82 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 25 Nov 2026 13:58:13 -0800 Subject: [PATCH 084/151] Color Wheel: tests for the remembered pick and the document's RGB space The remembered hue of a gray is dropped once the paint changes and the same gray comes back while the slider rows are hidden, and `ui.colorWheel {sliders: "oklch"}` follows the active document's RGB space. Both tests use the panel fixture that replaced the earlier harness. --- .../ui-egui/src/panels/tests_color_wheel.rs | 63 ++++++++++++++++++- 1 file changed, 62 insertions(+), 1 deletion(-) diff --git a/crates/ui-egui/src/panels/tests_color_wheel.rs b/crates/ui-egui/src/panels/tests_color_wheel.rs index 1485986f31..3cd0167b50 100644 --- a/crates/ui-egui/src/panels/tests_color_wheel.rs +++ b/crates/ui-egui/src/panels/tests_color_wheel.rs @@ -7,11 +7,72 @@ use std::rc::Rc; use craft::ui::testing::focus::AccessActionKind; use craft::ui::testing::{Fixture, Target}; use egui::{Key, Modifiers, vec2}; -use serde_json::Value; +use serde_json::{Value, json}; +use vectorcraft_engine::Session; use super::color_wheel::show; use crate::VectorcraftApp; +/// An app with a selected rectangle filled with `fill`. +fn app(fill: &str) -> VectorcraftApp { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 200, "height": 200})).unwrap(); + app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 50, "height": 50})).unwrap(); + app.run("paint.setFill", json!({"color": fill})).unwrap(); + app +} + +/// A hue given to a gray is remembered only until the document's next undo step: after the paint +/// changes and the same gray comes back while the rows are hidden, the rows show the gray's own hue. +#[test] +fn a_remembered_hue_is_dropped_after_the_paint_changes_while_the_rows_are_hidden() { + for (rows, hue) in [("hsl", "HSL Hue"), ("oklch", "Hue")] { + let mut a = app("#808080"); + a.run("ui.colorWheel", json!({"sliders": rows})).unwrap(); + let mut p = Panel::new(a); + p.set(hue, 240.0); + assert_eq!(p.number(hue), Some(240.0), "{rows}: the gray keeps the hue it was given"); + p.run("ui.colorWheel", json!({"sliders": "none"})); + p.run("paint.setFill", json!({"color": "#ff0000"})); + p.run("paint.setFill", json!({"color": "#808080"})); + p.run("ui.colorWheel", json!({"sliders": rows})); + assert_ne!(p.number(hue), Some(240.0), "{rows}: the remembered hue is dropped"); + } +} + +/// `sliders: "oklch"` follows the active document's RGB space: it is an error in a document assigned +/// Display P3 while the working RGB space is sRGB, and is taken in a document without a profile. +#[test] +fn oklch_sliders_follow_the_active_documents_rgb_space() { + const CHILD: &str = "VECTORCRAFT_TEST_COLOR_WHEEL_DOC_PROFILE"; + if std::env::var_os(CHILD).is_none() { + // Color settings are process-wide: assign the profile in a separate test process. + let output = std::process::Command::new(std::env::current_exe().unwrap()) + .args(["--exact", "panels::tests_color_wheel::oklch_sliders_follow_the_active_documents_rgb_space", "--nocapture"]) + .env(CHILD, "1") + .output() + .unwrap(); + let stdout = String::from_utf8_lossy(&output.stdout); + assert!( + output.status.success() && stdout.contains("test result: ok. 1 passed; 0 failed;"), + "isolated document profile test failed:\n{stdout}\n{}", + String::from_utf8_lossy(&output.stderr), + ); + return; + } + use vectorcraft_color::cms; + let mut a = app("#339966"); + a.run("file.new", json!({"width": 200, "height": 200})).unwrap(); + a.run("edit.assignProfile", json!({"rgb": cms::DISPLAY_P3})).unwrap(); + let mut p = Panel::new(a); + assert!(cms::working_settings().rgb != cms::DISPLAY_P3, "the working RGB space is not Display P3"); + let refused = p.app_mut().run("ui.colorWheel", json!({"sliders": "oklch"})); + assert!(refused.is_err(), "{refused:?}"); + p.run("document.activate", json!({"index": 0})); + p.run("ui.colorWheel", json!({"sliders": "oklch"})); + assert_eq!(p.app().ui.color_wheel.sliders, super::color_wheel::Sliders::Oklch); +} + /// The app shown through the panel's `show`, driven by the parts' names and keys. // PLAN: sh.SH4 `crate::testing::ui_context()` has no entry point on `Fixture` here, so the app's fonts are not installed. pub(super) struct Panel { From 6a71ec963894116609e2da23ec257437e9a6bcbf Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 25 Nov 2026 14:22:00 -0800 Subject: [PATCH 085/151] Tests: retype tests that expect an outline leave the installed fonts out Each test that expects a shape to stay an outline now passes `"installed": false`, so the fonts on the test machine do not change its result or its run time. With the installed fonts searched at tolerance 0.05, overlapping_exact_glyphs_stay_an_outline_when_near_matches_are_allowed ran past the CI job's limit. --- crates/engine/src/cmd/retype_tests.rs | 42 +++++++++++++++++---------- 1 file changed, 27 insertions(+), 15 deletions(-) diff --git a/crates/engine/src/cmd/retype_tests.rs b/crates/engine/src/cmd/retype_tests.rs index 2c24372150..b386758690 100644 --- a/crates/engine/src/cmd/retype_tests.rs +++ b/crates/engine/src/cmd/retype_tests.rs @@ -123,11 +123,13 @@ fn a_mark_in_one_font_starts_its_line_as_another_fonts_character() { #[test] fn a_combining_mark_starts_no_line() { // A combining mark on its own (a drawn dot, bar or ring is the same shape) stays an outline. + // The calls that leave a shape an outline leave the installed fonts out, so what this machine + // has installed does not change the result. let mut s = session(); let g = outlined(&mut s, json!({"x": 40, "y": 100, "text": "\u{312}", "size": 40, "font": "Source Sans 3", "style": "Regular"})); s.execute("select.set", &json!({"ids": [g]})).unwrap(); let before = s.doc().unwrap().doc.clone(); - let e = s.execute("type.retype", &json!({})).unwrap_err().to_string(); + let e = s.execute("type.retype", &json!({"installed": false})).unwrap_err().to_string(); assert!(e.contains("no selected shape matches"), "{e}"); assert!(s.doc().unwrap().doc == before, "nothing changes"); // A shape that is both a mark (tilde below) and a character (small tilde) starts its line as @@ -145,7 +147,7 @@ fn a_combining_mark_starts_no_line() { let g = outlined(&mut s, json!({"x": 40, "y": 200, "text": "\u{312}ab", "size": 40, "font": "Source Sans 3", "style": "Regular"})); let mark = s.doc().unwrap().doc.children(Some(NodeId(g))).unwrap()[0].id.0; s.execute("select.set", &json!({"ids": [g]})).unwrap(); - let r = s.execute("type.retype", &json!({})).unwrap(); + let r = s.execute("type.retype", &json!({"installed": false})).unwrap(); assert_eq!(r["texts"], json!(["ab"]), "{r}"); assert_eq!(r["unmatched"], json!([mark])); // After a base, the mark is retyped with it. @@ -160,7 +162,7 @@ fn a_combining_mark_starts_no_line() { s.execute("select.set", &json!({"ids": [mark]})).unwrap(); s.execute("object.move", &json!({"dx": 3, "dy": 0})).unwrap(); s.execute("select.set", &json!({"ids": [g]})).unwrap(); - let r = s.execute("type.retype", &json!({})).unwrap(); + let r = s.execute("type.retype", &json!({"installed": false})).unwrap(); assert_eq!((&r["texts"], &r["unmatched"]), (&json!(["x", "yz"]), &json!([mark])), "{r}"); // A mark that is also another character (dot below, dot above) becomes that character there. let g = outlined(&mut s, json!({"x": 300, "y": 120, "text": "x\u{323}yz", "size": 40, "font": "Source Sans 3", "style": "Regular"})); @@ -183,7 +185,7 @@ fn a_combining_mark_starts_no_line() { s.execute("select.set", &json!({"ids": [mark]})).unwrap(); s.execute("object.move", &json!({"dx": 3, "dy": 0})).unwrap(); s.execute("select.set", &json!({"ids": [g]})).unwrap(); - let r = s.execute("type.retype", &json!({})).unwrap(); + let r = s.execute("type.retype", &json!({"installed": false})).unwrap(); assert_eq!((&r["texts"], &r["unmatched"]), (&json!(["x", "yzw"]), &json!([mark])), "{r}"); assert_eq!(r["fonts"][1]["tracking"], json!(50.0), "{r}"); // A one-contour glyph after a mark that stays an outline (a bar, then a dot) is alone, and @@ -193,7 +195,7 @@ fn a_combining_mark_starts_no_line() { pair.sort_unstable(); let word = outlined(&mut s, json!({"x": 40, "y": 380, "text": "ab", "size": 40, "font": "Source Sans 3", "style": "Regular"})); s.execute("select.set", &json!({"ids": [dot, word]})).unwrap(); - let r = s.execute("type.retype", &json!({})).unwrap(); + let r = s.execute("type.retype", &json!({"installed": false})).unwrap(); assert_eq!(r["texts"], json!(["ab"]), "{r}"); let mut left: Vec = r["unmatched"].as_array().unwrap().iter().map(|v| v.as_u64().unwrap()).collect(); left.sort_unstable(); @@ -246,7 +248,8 @@ fn marks_first_after_a_split_leave_other_lines_their_tracking() { s.execute("select.set", &json!({"ids": moved})).unwrap(); s.execute("object.move", &json!({"dx": 3, "dy": 0})).unwrap(); s.execute("select.set", &json!({"ids": [marks, tracked]})).unwrap(); - let r = s.execute("type.retype", &json!({})).unwrap(); + // The installed fonts left out: what this machine has installed does not change the result. + let r = s.execute("type.retype", &json!({"installed": false})).unwrap(); let texts = r["texts"].as_array().unwrap(); let at = texts.iter().position(|t| t == "yzw").unwrap_or_else(|| panic!("yzw in {r}")); assert_eq!(r["fonts"][at]["tracking"], json!(50.0), "{r}"); @@ -488,7 +491,8 @@ fn a_glyph_painted_beyond_what_type_takes_stays_an_outline() { }) .unwrap(); s.execute("select.set", &json!({"ids": [g]})).unwrap(); - let r = s.execute("type.retype", &json!({})).unwrap(); + // The installed fonts left out: what this machine has installed does not change the result. + let r = s.execute("type.retype", &json!({"installed": false})).unwrap(); assert_eq!(r["texts"], json!(["B"]), "two fills: A stays an outline: {r}"); assert_eq!(r["unmatched"], json!([a])); } @@ -755,7 +759,8 @@ fn simplified_outlines_retype_only_with_a_tolerance_and_report_their_score() { simplify_every_path(&mut s, 0.05); s.execute("select.set", &json!({"ids": [g]})).unwrap(); let before = s.doc().unwrap().doc.clone(); - let e = s.execute("type.retype", &json!({})).unwrap_err().to_string(); + // The installed fonts left out: what this machine has installed does not change the result. + let e = s.execute("type.retype", &json!({"installed": false})).unwrap_err().to_string(); assert!(e.contains("no selected shape matches"), "no exact match: {e}"); for bad in [json!(-0.01), json!(0.06), json!("0.02"), json!(true), json!(null)] { let e = s.execute("type.retype", &json!({"tolerance": bad})).unwrap_err().to_string(); @@ -1365,7 +1370,8 @@ fn a_lone_period_in_a_compound_selected_alone_stays_an_outline() { let c = s.execute("object.compoundPath.make", &json!({})).unwrap()["id"].as_u64().unwrap(); s.execute("select.set", &json!({"ids": [c]})).unwrap(); let before = s.doc().unwrap().doc.clone(); - let e = match s.execute("type.retype", &json!({})) { + // The installed fonts left out: what this machine has installed does not change the result. + let e = match s.execute("type.retype", &json!({"installed": false})) { Ok(r) => panic!("the period became type: {r}"), Err(e) => e.to_string(), }; @@ -1425,7 +1431,8 @@ fn a_compound_whose_parts_are_not_all_glyphs_stays_whole() { let c = s.execute("object.compoundPath.make", &json!({})).unwrap()["id"].as_u64().unwrap(); s.execute("select.set", &json!({"ids": [c]})).unwrap(); let before = s.doc().unwrap().doc.clone(); - let e = s.execute("type.retype", &json!({})).unwrap_err().to_string(); + // The installed fonts left out: what this machine has installed does not change the result. + let e = s.execute("type.retype", &json!({"installed": false})).unwrap_err().to_string(); assert!(e.contains("(1 checked)"), "reported once: {e}"); assert!(s.doc().unwrap().doc == before, "nothing changes"); } @@ -1442,7 +1449,8 @@ fn glyphs_that_overlap_in_an_even_odd_compound_stay_an_outline() { let c = s.execute("object.compoundPath.make", &json!({})).unwrap()["id"].as_u64().unwrap(); s.execute("select.set", &json!({"ids": [c]})).unwrap(); let before = s.doc().unwrap().doc.clone(); - let e = match s.execute("type.retype", &json!({})) { + // The installed fonts left out: what this machine has installed does not change the result. + let e = match s.execute("type.retype", &json!({"installed": false})) { Ok(r) => panic!("the overlapping o's became type: {r}"), Err(e) => e.to_string(), }; @@ -1483,7 +1491,8 @@ fn a_translucent_compound_whose_glyphs_overlap_stays_an_outline() { }) .unwrap(); s.execute("select.set", &json!({"ids": [c]})).unwrap(); - let r = s.execute("type.retype", &json!({})); + // The installed fonts left out: what this machine has installed does not change the result. + let r = s.execute("type.retype", &json!({"installed": false})); if opacity == 1.0 { let r = r.unwrap(); assert_eq!(r["texts"], json!(["i", "i"]), "opaque, the two lines become type: {r}"); @@ -1504,8 +1513,9 @@ fn overlapping_exact_glyphs_stay_an_outline_when_near_matches_are_allowed() { s.execute("select.set", &json!({"ids": kids})).unwrap(); let c = s.execute("object.compoundPath.make", &json!({})).unwrap()["id"].as_u64().unwrap(); s.execute("select.set", &json!({"ids": [c]})).unwrap(); + // The installed fonts left out: what this machine has installed does not change the result. for tolerance in [0.0, 0.05] { - if let Ok(r) = s.execute("type.retype", &json!({"tolerance": tolerance})) { + if let Ok(r) = s.execute("type.retype", &json!({"tolerance": tolerance, "installed": false})) { panic!("the overlapping o's became type at dx {dx}, tolerance {tolerance}: {r}"); } } @@ -1566,7 +1576,8 @@ fn a_glyph_with_only_some_contours_turned_in_an_even_odd_compound_still_becomes_ }) .unwrap(); s.execute("select.set", &json!({"ids": [c]})).unwrap(); - assert!(s.execute("type.retype", &json!({})).is_err(), "nonzero, contour {turned} turned paints the counter"); + // The installed fonts left out: what this machine has installed does not change the result. + assert!(s.execute("type.retype", &json!({"installed": false})).is_err(), "nonzero, contour {turned} turned paints the counter"); s.execute("path.setFillRule", &json!({"rule": "evenOdd", "ids": [c]})).unwrap(); let r = s.execute("type.retype", &json!({})).unwrap(); assert_eq!(r["texts"], json!(["do"]), "contour {turned} turned: {r}"); @@ -1593,7 +1604,8 @@ fn a_compound_whose_glyph_stays_an_outline_keeps_its_other_glyphs_too() { let r = s.execute("shape.rectangle", &json!({"x": 300, "y": 300, "width": 40, "height": 20})).unwrap()["id"].as_u64().unwrap(); s.execute("select.set", &json!({"ids": [c, r]})).unwrap(); let before = s.doc().unwrap().doc.clone(); - let e = match s.execute("type.retype", &json!({})) { + // The installed fonts left out: what this machine has installed does not change the result. + let e = match s.execute("type.retype", &json!({"installed": false})) { Ok(r) => panic!("the A became type without its period: {r}"), Err(e) => e.to_string(), }; From 1285de28efd4e742df73846193eefb42756f9229 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 25 Nov 2026 14:57:55 -0800 Subject: [PATCH 086/151] Retype: plain shapes alone run the command at once A selection of plain shapes (rectangles, bars) no longer starts a background search of the installed fonts, which would read no font for them. The command runs at once, as it does with `installed` false. --- crates/engine/src/cmd/retype_installed.rs | 8 +++----- crates/engine/src/cmd/retype_installed_tests.rs | 14 ++++++++++++++ 2 files changed, 17 insertions(+), 5 deletions(-) diff --git a/crates/engine/src/cmd/retype_installed.rs b/crates/engine/src/cmd/retype_installed.rs index eda6e1105b..a113982379 100644 --- a/crates/engine/src/cmd/retype_installed.rs +++ b/crates/engine/src/cmd/retype_installed.rs @@ -605,8 +605,8 @@ pub(super) fn handed(s: &mut Session) -> Option { impl RetypeRun { /// The search `command` (`type.retype` or `type.retypeFonts`) with params `p` makes in the - /// active document. None when it reads no installed font: `installed` is false, or no shape has - /// a glyph's key. An error where the command fails on its params or on the selection. + /// active document. None when it reads no installed font: `installed` is false, or no shape + /// starts a search ([`starts`]: each is plain or has no glyph's key). An error where the command fails on its params or on the selection. /// The faces to compare are picked when the search runs. pub fn prepare(s: &Session, command: &str, p: &Value) -> Result> { let (command, fonts, tolerance) = match command { @@ -641,9 +641,7 @@ impl RetypeRun { } else { pieces.into_iter().map(|pc| Shape::whole(pc.path)).collect() }; - let sought: Vec = shapes.iter().map(Shape::sought).collect(); - let (keys, near) = keys_of(&sought, tolerance); - if keys.is_empty() && near.is_empty() { + if !shapes.iter().any(|s| starts(&s.sought(), tolerance)) { return Ok(None); } let faces = Faces::Of { doc: st.doc.clone(), fonts }; diff --git a/crates/engine/src/cmd/retype_installed_tests.rs b/crates/engine/src/cmd/retype_installed_tests.rs index 8db2c1ab12..53c7a6bd04 100644 --- a/crates/engine/src/cmd/retype_installed_tests.rs +++ b/crates/engine/src/cmd/retype_installed_tests.rs @@ -353,6 +353,20 @@ fn a_run_away_from_the_command_loads_the_faces_it_finds() { assert!(!run.current(&s)); } +#[test] +fn plain_shapes_alone_start_no_run_away_from_the_command() { + // A rectangle and a bar are plain: the search reads no installed font for them, so the + // command runs at once. + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 600, "height": 400})).unwrap(); + let rect = s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 80, "height": 40})).unwrap()["id"].as_u64().unwrap(); + let bar = s.execute("shape.rectangle", &json!({"x": 10, "y": 100, "width": 4, "height": 60})).unwrap()["id"].as_u64().unwrap(); + s.execute("select.set", &json!({"ids": [rect, bar]})).unwrap(); + for (cmd, p) in [("type.retype", json!({})), ("type.retype", json!({"tolerance": 0.05})), ("type.retypeFonts", json!({}))] { + assert!(super::RetypeRun::prepare(&s, cmd, &p).unwrap().is_none(), "{cmd} {p}"); + } +} + #[test] fn what_a_search_found_is_handed_to_the_next_command_in_its_document() { let mut s = Session::new(); From 6ad8c0476a1a7775df23ef61b07f13d1dea5fe9b Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 25 Nov 2026 15:13:55 -0800 Subject: [PATCH 087/151] Scripts: script.grants.revoke removes only the grant named as given script.grants.revoke matched a path both as given and with its links followed, so revoking a grant whose path is now a link to another granted path removed both grants. The spellings are now tried in order, the path as given first, and only the first script and path pair that some grant holds is removed. --- crates/engine/src/cmd/scripts.rs | 6 ++--- crates/engine/src/script/files.rs | 22 +++++++++++++---- crates/engine/src/tests/script_io.rs | 35 ++++++++++++++++++++++++++++ docs/mcp.md | 2 +- 4 files changed, 57 insertions(+), 8 deletions(-) diff --git a/crates/engine/src/cmd/scripts.rs b/crates/engine/src/cmd/scripts.rs index 14ad0685fd..31a78f0ed3 100644 --- a/crates/engine/src/cmd/scripts.rs +++ b/crates/engine/src/cmd/scripts.rs @@ -104,7 +104,7 @@ pub fn specs() -> Vec { "Revoke Script File Permissions", [], None, - "{script?: a script file's path, path?: an allowed file or folder's path, all?: true (exactly one of all and the other two)} remove the kept file access of that script, of that path, of both together, or every one; a path is matched as given and as script.grants lists it, after its links are followed (a path outside the automation read roots is matched as given only); refused with the busy error while a script runs, as the run keeps the grants it started with → {removed: how many}", + "{script?: a script file's path, path?: an allowed file or folder's path, all?: true (exactly one of all and the other two)} remove the kept file access of that script, of that path, of both together, or every one; a path is matched as given, as script.grants lists it, or after its links are followed when no grant holds it as given (a path outside the automation read roots is matched as given only); refused with the busy error while a script runs, as the run keeps the grants it started with → {removed: how many}", always, grants_revoke ), @@ -384,8 +384,8 @@ fn grants(s: &mut Session, _: &Value) -> Result { fn grants_revoke(s: &mut Session, p: &Value) -> Result { const C: &str = "script.grants.revoke"; - // A path is matched as given, and also with its links followed, so a grant whose path a link - // has since taken the place of is still removed. A path the request may not read (outside the + // A path is matched as given, or with its links followed when no grant holds it as given, so a + // grant whose path a link has since taken the place of is still removed. A path the request may not read (outside the // automation read roots, a network path among them) is compared as written, without looking it up. let path_of = |key: &str| match p.get(key) { None => Ok(None), diff --git a/crates/engine/src/script/files.rs b/crates/engine/src/script/files.rs index a914f2d474..9d4c90aed4 100644 --- a/crates/engine/src/script/files.rs +++ b/crates/engine/src/script/files.rs @@ -1079,15 +1079,29 @@ pub(crate) fn stored_grants(data_dir: &Path) -> std::io::Result, path: Option<&[String]>) -> std::io::Result { let store = data_dir.with_file_name(GRANTS_FILE); let _lock = lock_store(&store)?; let grants = try_read_store(&store)?; let before = grants.len(); - let matches = |value: &serde_json::Value, names: Option<&[String]>| names.is_none_or(|names| names.iter().any(|n| value == n.as_str())); - let kept: Vec = grants.into_iter().filter(|g| !(matches(&g["script"], script) && matches(&g["path"], path))).collect(); + // `None` matches any value; `Some(name)` only that name. + fn spellings(names: Option<&[String]>) -> Vec> { + match names { + None => vec![None], + Some(names) => names.iter().map(|n| Some(n.as_str())).collect(), + } + } + let matches = |g: &serde_json::Value, (script, path): (Option<&str>, Option<&str>)| { + script.is_none_or(|s| g["script"] == s) && path.is_none_or(|p| g["path"] == p) + }; + let pairs = spellings(script).into_iter().flat_map(|s| spellings(path).into_iter().map(move |p| (s, p))); + let pair = pairs.into_iter().find(|&pair| grants.iter().any(|g| matches(g, pair))); + let Some(pair) = pair else { return Ok(0) }; + let kept: Vec = grants.into_iter().filter(|g| !matches(g, pair)).collect(); let removed = before - kept.len(); if removed > 0 { write_store(&store, kept)?; diff --git a/crates/engine/src/tests/script_io.rs b/crates/engine/src/tests/script_io.rs index d4eed1b4f4..0f05c839c4 100644 --- a/crates/engine/src/tests/script_io.rs +++ b/crates/engine/src/tests/script_io.rs @@ -674,6 +674,41 @@ fn a_grant_whose_path_is_now_a_link_is_revoked_by_its_listed_path() { let _ = std::fs::remove_dir_all(base); } +/// A grant kept for a path that is now a link to another granted path is revoked alone: the grant of +/// the link's target stays. +#[cfg(unix)] +#[test] +fn revoking_a_grant_whose_path_now_links_to_another_grant_keeps_the_other() { + let base = folder("grants-relinked-both"); + let real = std::fs::canonicalize(&base).unwrap(); + let (kept, other) = (real.join("kept.txt"), real.join("other.txt")); + write(&other, b"other"); + let (kept_path, other_path) = (kept.to_string_lossy().into_owned(), other.to_string_lossy().into_owned()); + let grant = |path: &str| json!({"script": "/s.jsx", "sha256": "0", "code": [], "path": path, "write": false, "folder": false}); + let stored = json!({"version": 1, "grants": [grant(&kept_path), grant(&other_path)]}); + write(&base.join("settings/Script Grants.json"), stored.to_string().as_bytes()); + std::os::unix::fs::symlink(&other, &kept).unwrap(); + let mut s = with_data(&base); + let r = s.execute("script.grants.revoke", &json!({"script": "/s.jsx", "path": kept_path})).unwrap(); + assert_eq!(r["removed"], 1, "{r}"); + let left = s.execute("script.grants", &json!({})).unwrap(); + let paths: Vec = left["grants"].as_array().into_iter().flatten().map(|g| g["path"].clone()).collect(); + assert_eq!(paths, [json!(other_path)], "{left}"); + // Another script's grant of the path as given does not keep this script's grant of the link's + // target from being removed. + let stored = json!({"version": 1, "grants": [ + {"script": "/t.jsx", "sha256": "0", "code": [], "path": kept_path, "write": false, "folder": false}, + grant(&other_path) + ]}); + write(&base.join("settings/Script Grants.json"), stored.to_string().as_bytes()); + let r = s.execute("script.grants.revoke", &json!({"script": "/s.jsx", "path": kept_path})).unwrap(); + assert_eq!(r["removed"], 1, "{r}"); + let left = s.execute("script.grants", &json!({})).unwrap(); + let scripts: Vec = left["grants"].as_array().into_iter().flatten().map(|g| g["script"].clone()).collect(); + assert_eq!(scripts, [json!("/t.jsx")], "{left}"); + let _ = std::fs::remove_dir_all(base); +} + /// Reading and changing the grants file wait for a lock another handle holds only for a bounded /// number of tries: then a listing and a change fail, with the file unchanged. A lock /// released while it waits is taken. diff --git a/docs/mcp.md b/docs/mcp.md index 2846f7d7c8..45555fd57f 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -3161,7 +3161,7 @@ takes its place), and `file` the grants file's path, or `null` without a settings folder. Under automation read roots, a `script`, `path` or `file` outside them is given as its file name alone. `script.grants.revoke {script?, path?, all?}` removes the grants of a script file, of a path, of both together, or with `all: true` every grant, and returns `{removed}`. A path is -matched as given and after its links are followed; under automation read roots, a path outside them is matched as given only. While a script +matched as given, or after its links are followed when no grant holds it as given; under automation read roots, a path outside them is matched as given only. While a script runs it is refused with the busy error, as the run keeps the grants it started with. A grants file that is there but cannot be read, a link to a missing file included, is left as it is: `script.grants` and `script.grants.revoke` fail, and a grant picked with Always is not kept. A missing grants file lists no grants, and `script.grants` leaves out a grant in the file that is not well From f341cb5b0d8834da90d684dfe1df076c39577a60 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 25 Nov 2026 15:22:31 -0800 Subject: [PATCH 088/151] Scripts: a chosen script keeps script.run's reply with startup scripts on With Run Startup Scripts on, ui.runScript and ui.runInstalledScript return script.run's reply, or its error when the chosen script cannot start, with the startup run's reply under startup. While a startup script runs first, the reply is {running: true, queued: true}. --- crates/mcp/src/ui_catalog.rs | 4 +-- crates/ui-egui/src/menus/ui_commands.rs | 4 +-- crates/ui-egui/src/script_runs.rs | 22 ++++++++++++++-- crates/ui-egui/src/tests/scripts_menu.rs | 33 ++++++++++++++++++++++++ docs/mcp.md | 5 +++- 5 files changed, 61 insertions(+), 7 deletions(-) diff --git a/crates/mcp/src/ui_catalog.rs b/crates/mcp/src/ui_catalog.rs index 18d0ebc247..82e0fc6489 100644 --- a/crates/mcp/src/ui_catalog.rs +++ b/crates/mcp/src/ui_catalog.rs @@ -2022,13 +2022,13 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "ui.runScript", "Other Script…", "Cmd+F12", - "{path? | source?, name?} run a .js or .jsx file (script.run), after the warning unless Preferences › General › Show External Script Warning is off (dialog `scriptRun`: `name`, `script`, `dontShow`); without a file pick one (the web opens the browser's file picker)", + "{path? | source?, name?} run a .js or .jsx file (script.run), after the warning unless Preferences › General › Show External Script Warning is off (dialog `scriptRun`: `name`, `script`, `dontShow`); without a file pick one (the web opens the browser's file picker); with Preferences › General › Run Startup Scripts on, the startup scripts run first (script.startup.run) and script.run's reply also holds `startup`, script.startup.run's reply; while a startup script runs before it the reply is {running: true, queued: true}, and a later failure to start shows in the status bar", ), ( "ui.runInstalledScript", "Run Script", "", - "{path: a script's path as script.listInstalled gives it} run a script of the Scripts folder, as its File › Scripts item does (script.run with installed reads the file once, checks it again and runs that text, so its #include lines and $.evalFile read in the folder that read found), without the warning Other Script… shows; a file that is no longer a .js or .jsx file in the folder or a subfolder at most 4 levels below it, or that is or lies behind a link or is hidden, is not run, and the menu's listing is read again", + "{path: a script's path as script.listInstalled gives it} run a script of the Scripts folder, as its File › Scripts item does (script.run with installed reads the file once, checks it again and runs that text, so its #include lines and $.evalFile read in the folder that read found), without the warning Other Script… shows; a file that is no longer a .js or .jsx file in the folder or a subfolder at most 4 levels below it, or that is or lies behind a link or is hidden, is not run, and the menu's listing is read again; with Preferences › General › Run Startup Scripts on, the startup scripts run first (script.startup.run) and script.run's reply also holds `startup`, script.startup.run's reply; while a startup script runs before it the reply is {running: true, queued: true}, and a later failure to start shows in the status bar", ), ( "ui.checkScript", diff --git a/crates/ui-egui/src/menus/ui_commands.rs b/crates/ui-egui/src/menus/ui_commands.rs index f67f316f5f..8ebfe0d9c6 100644 --- a/crates/ui-egui/src/menus/ui_commands.rs +++ b/crates/ui-egui/src/menus/ui_commands.rs @@ -2023,13 +2023,13 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "ui.runScript", "Other Script…", "Cmd+F12", - "{path? | source?, name?} run a .js or .jsx file (script.run), after the warning unless Preferences › General › Show External Script Warning is off (dialog `scriptRun`: `name`, `script`, `dontShow`); without a file pick one (the web opens the browser's file picker)", + "{path? | source?, name?} run a .js or .jsx file (script.run), after the warning unless Preferences › General › Show External Script Warning is off (dialog `scriptRun`: `name`, `script`, `dontShow`); without a file pick one (the web opens the browser's file picker); with Preferences › General › Run Startup Scripts on, the startup scripts run first (script.startup.run) and script.run's reply also holds `startup`, script.startup.run's reply; while a startup script runs before it the reply is {running: true, queued: true}, and a later failure to start shows in the status bar", ), ( crate::scripts_menu::COMMAND, "Run Script", "", - "{path: a script's path as script.listInstalled gives it} run a script of the Scripts folder, as its File › Scripts item does (script.run with installed reads the file once, checks it again and runs that text, so its #include lines and $.evalFile read in the folder that read found), without the warning Other Script… shows; a file that is no longer a .js or .jsx file in the folder or a subfolder at most 4 levels below it, or that is or lies behind a link or is hidden, is not run, and the menu's listing is read again", + "{path: a script's path as script.listInstalled gives it} run a script of the Scripts folder, as its File › Scripts item does (script.run with installed reads the file once, checks it again and runs that text, so its #include lines and $.evalFile read in the folder that read found), without the warning Other Script… shows; a file that is no longer a .js or .jsx file in the folder or a subfolder at most 4 levels below it, or that is or lies behind a link or is hidden, is not run, and the menu's listing is read again; with Preferences › General › Run Startup Scripts on, the startup scripts run first (script.startup.run) and script.run's reply also holds `startup`, script.startup.run's reply; while a startup script runs before it the reply is {running: true, queued: true}, and a later failure to start shows in the status bar", ), ( "ui.checkScript", diff --git a/crates/ui-egui/src/script_runs.rs b/crates/ui-egui/src/script_runs.rs index 5b5ffc099b..d9c9960ac0 100644 --- a/crates/ui-egui/src/script_runs.rs +++ b/crates/ui-egui/src/script_runs.rs @@ -124,12 +124,30 @@ fn ask(app: &mut VectorcraftApp) -> bool { /// the startup scripts when General › Run Startup Scripts is on (`script.startup.run`). A startup /// script that cannot start, a listing of the Startup Scripts folder that was not read in full, and /// a folder that is there and cannot be read show in the status bar ([`reply_notes`]). +/// → `script.run`'s reply, with `startup` holding `script.startup.run`'s when the startup scripts +/// were run: the chosen script's own reply when it ran to its end at once, `{running: true, name}` +/// when it is running, or `{running: true, queued: true}` while a startup script runs before it. +/// A chosen script that could not start gives its error, as `script.run` does. pub(crate) fn run_chosen(app: &mut VectorcraftApp, params: Value) -> Result { if app.session.startup_skip().is_some() { return app.run("script.run", params); } - let reply = app.run("script.startup.run", json!({"reason": "menu", "then": params}))?; - reply_notes(app, &reply); + let mut startup = app.run("script.startup.run", json!({"reason": "menu", "then": params}))?; + reply_notes(app, &startup); + let mut reply = match startup.as_object_mut().and_then(|o| o.remove("then")) { + Some(then) => then, + // Nothing runs and the chosen script gave no reply: it could not start, and it is the + // last of the runs that could not start. + None if !app.session.script_running() => { + let last = startup["failed"].as_array().and_then(|failed| failed.last()); + return Err(last.and_then(|failed| failed["error"].as_str()).unwrap_or_default().to_string()); + } + None if app.session.startup_script_running() => json!({"running": true, "queued": true}), + None => json!({"running": true, "name": app.session.script_name().unwrap_or_default()}), + }; + if let Some(o) = reply.as_object_mut() { + o.insert("startup".to_string(), startup); + } Ok(reply) } diff --git a/crates/ui-egui/src/tests/scripts_menu.rs b/crates/ui-egui/src/tests/scripts_menu.rs index ce1dfdfae8..e0604081fd 100644 --- a/crates/ui-egui/src/tests/scripts_menu.rs +++ b/crates/ui-egui/src/tests/scripts_menu.rs @@ -525,6 +525,39 @@ fn with_run_startup_scripts_on_other_script_and_the_launch_run_the_startup_scrip let _ = std::fs::remove_dir_all(dir); } +#[test] +fn with_run_startup_scripts_on_a_chosen_script_still_replies_as_script_run() { + let dir = folder("startup-reply"); + let mut app = app(&dir); + app.session.prefs.show_external_script_warning = false; + let off = menus::run_ui_command(&mut app, "ui.runScript", &json!({ "source": DRAW, "name": "chosen" })).unwrap().unwrap(); + finish(&mut app); + assert_eq!(off, json!({"running": true, "name": "chosen"})); + let empty = dir.join("Startup Scripts"); + std::fs::create_dir_all(&empty).unwrap(); + app.session.attach_startup_scripts_dir(empty); + app.run("prefs.set", json!({"key": "runStartupScripts", "value": true})).unwrap(); + // An empty folder: the chosen script starts at once, named as its run is, by a #script line too. + let r = menus::run_ui_command(&mut app, "ui.runScript", &json!({ "source": DRAW, "name": "chosen" })).unwrap().unwrap(); + finish(&mut app); + assert_eq!((&r["running"], &r["name"], &r["startup"]["queued"]), (&json!(true), &json!("chosen"), &json!(1)), "{r}"); + let named = format!("#script \"Named\"\n{DRAW}"); + let r = menus::run_ui_command(&mut app, "ui.runScript", &json!({ "source": named })).unwrap().unwrap(); + finish(&mut app); + assert_eq!(r["name"], "Named", "{r}"); + // A chosen script that cannot start gives its error, as script.run does. + let alone = app.run("script.run", json!({"source": "vc.log(("})).unwrap_err(); + let e = menus::run_ui_command(&mut app, "ui.runScript", &json!({ "source": "vc.log((" })).unwrap().unwrap_err(); + assert_eq!(e, alone); + // A startup script runs first: the chosen script is queued after it. + startup_folder(&mut app, &dir); + let r = menus::run_ui_command(&mut app, "ui.runScript", &json!({ "source": DRAW, "name": "chosen" })).unwrap().unwrap(); + finish(&mut app); + assert_eq!((&r["running"], &r["queued"], &r["startup"]["queued"]), (&json!(true), &json!(true), &json!(2)), "{r}"); + assert_eq!(started(&app).last().map(String::as_str), Some("chosen")); + let _ = std::fs::remove_dir_all(dir); +} + #[test] fn a_stopped_startup_script_says_it_was_stopped_and_the_chosen_script_still_runs() { let dir = folder("startup-stop"); diff --git a/docs/mcp.md b/docs/mcp.md index 56557457bb..8311998f81 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -3311,7 +3311,10 @@ reply is `{reason, skipped: false, running, queued, failed, disabled, truncated, the runs that could not start before the first one did. Each run then reports as a `script.run` in the app does, the next one starts at the frame after, and a later run that cannot start, the chosen script included, is named in the status bar. Stop (`script.stop`) asked for between two runs stops the run that starts next. Under `--automation-read-root` it reads the folder only when the folder lies inside a -read root. +read root. With the preference on, `ui.runScript` and `ui.runInstalledScript` still return `script.run`'s reply, +or its error when the chosen script cannot start, and add `startup` holding the `script.startup.run` reply. While a +startup script runs before the chosen script, that reply is `{running: true, queued: true}`, and a chosen script that +then cannot start is named in the status bar. ```sh vectorcraft-cli run --cmd script.startup.run --params '{"reason": "launch"}' From 83184e76bda85636774bea3577f1c9dafa12172b Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 25 Nov 2026 17:33:55 -0800 Subject: [PATCH 089/151] Scripts: stopping from the quit prompt between startup runs drops the queued runs A startup script refused before it begins, such as with an undo group open, is named in the Script Console. Stopping the runs from the quit prompt between two queued runs drops the runs not yet started, and the status bar says so. While that prompt is open, or before its answer is taken, the next run does not start. --- crates/engine/src/cmd/scripts.rs | 10 ++++- crates/engine/src/script/mod.rs | 6 ++- crates/engine/tests/script_startup.rs | 33 ++++++++++++++ crates/ui-egui/src/dialogs/script_run.rs | 37 ++++++++++++--- crates/ui-egui/src/script_runs.rs | 19 ++++++++ crates/ui-egui/src/tests/script_run.rs | 57 ++++++++++++++++++++++++ docs/mcp.md | 3 +- 7 files changed, 155 insertions(+), 10 deletions(-) diff --git a/crates/engine/src/cmd/scripts.rs b/crates/engine/src/cmd/scripts.rs index 8cec1db4f6..a683a0f51d 100644 --- a/crates/engine/src/cmd/scripts.rs +++ b/crates/engine/src/cmd/scripts.rs @@ -417,7 +417,7 @@ impl Session { self.startup_loading = Some(vectorcraft_plugins::safe_mode::loading(&item)); let locale = script::dollar::ui_locale(self.ui_language.as_deref().unwrap_or(&self.prefs.interface_language)); let request = script::Request { - name, + name: name.clone(), name_given: false, file: Some(path.to_string_lossy().into_owned()), checked_real: Some(real), @@ -427,9 +427,15 @@ impl Session { locale, answers: vec![], }; + let runs = self.script_runs; self.script_start(request).map_err(|e| { self.startup_ended(); - e.to_string() + let message = e.to_string(); + // A run refused before it began, such as with an undo group open, has no console entry yet. + if self.script_runs == runs { + self.note_unread(&name, &message); + } + message }) } diff --git a/crates/engine/src/script/mod.rs b/crates/engine/src/script/mod.rs index 731e469c6d..f617a761f3 100644 --- a/crates/engine/src/script/mod.rs +++ b/crates/engine/src/script/mod.rs @@ -1919,13 +1919,15 @@ impl Session { } /// Stops the running script at once and puts everything back, with the report of a stopped run - /// ([`Self::script_report`]). False with none running. + /// ([`Self::script_report`]). Between two runs `script.startup.run` queued, the queued runs are + /// not started, and the report stays the last run's. False with none running or queued. pub fn script_abandon(&mut self) -> bool { // The runs queued after it are not started. + let queued = !self.script_queue.is_empty(); self.script_queue.clear(); self.script_queue_scope = None; self.startup_ended(); - let Some(key) = self.script_key.take() else { return false }; + let Some(key) = self.script_key.take() else { return queued }; let Some(job) = JOBS.with(|jobs| jobs.borrow_mut().remove(&key.id)) else { self.script_gone(key, console::Ending::Stopped); return true; diff --git a/crates/engine/tests/script_startup.rs b/crates/engine/tests/script_startup.rs index f6ca150ded..f6f423da89 100644 --- a/crates/engine/tests/script_startup.rs +++ b/crates/engine/tests/script_startup.rs @@ -345,6 +345,39 @@ fn in_the_app_a_stop_between_two_runs_stops_the_run_that_starts_next() { } } +#[test] +fn a_startup_script_refused_before_it_begins_is_in_the_script_console() { + let _f = fresh(); + let dir = tmp_dir("refused"); + write(&dir, "a.jsx", "vc.log(1);"); + let mut s = session(&dir); + s.execute("file.new", &json!({})).unwrap(); + s.execute("edit.undoGroup.begin", &json!({})).unwrap(); + let r = s.execute("script.startup.run", &json!({"reason": "launch"})).unwrap(); + let error = r["failed"][0]["error"].as_str().unwrap().to_string(); + assert!(error.contains("undo group"), "{r}"); + assert_eq!(started(&s), ["a.jsx"]); + assert_eq!(console(&s, "error"), [format!("a.jsx: {error}")]); +} + +#[test] +fn in_the_app_abandoning_between_two_runs_drops_the_queued_runs() { + let _f = fresh(); + let dir = tmp_dir("app-abandon-between"); + write(&dir, "a.jsx", "vc.log(1);"); + write(&dir, "b.jsx", "vc.log(2);"); + let mut s = session(&dir); + s.script_frames = true; + let then = json!({"source": "vc.log(3);", "name": "chosen"}); + s.execute("script.startup.run", &json!({"reason": "menu", "then": then})).unwrap(); + assert_eq!((0..10_000).find_map(|_| s.script_pump()).unwrap().unwrap()["ok"], true, "a.jsx ends"); + assert!(s.script_running() && s.script_name().is_none(), "b.jsx waits for the next pump"); + assert!(s.script_abandon(), "the queued runs are stopped"); + assert!(!s.script_running()); + assert!(s.script_pump().is_none()); + assert_eq!(started(&s), ["a.jsx"]); +} + #[test] fn in_the_app_startup_scripts_that_cannot_start_are_in_the_reply() { let _f = fresh(); diff --git a/crates/ui-egui/src/dialogs/script_run.rs b/crates/ui-egui/src/dialogs/script_run.rs index f7f005d9fa..08994f11d7 100644 --- a/crates/ui-egui/src/dialogs/script_run.rs +++ b/crates/ui-egui/src/dialogs/script_run.rs @@ -408,6 +408,11 @@ pub(crate) fn with_host(app: &VectorcraftApp, f: impl FnOnce(&mut DialogHost, Some(app.dialogs()?.with(|host| f(host, &ctx))) } +/// Whether the question asked on quitting with a script running is open. +pub(crate) fn asking_to_close(app: &VectorcraftApp) -> bool { + with_host(app, |host, _| host.is_open::()).unwrap_or(false) +} + /// Whether a dialog is open or waits to open: a script's dialog opens only over nothing. pub(crate) fn busy(app: &VectorcraftApp) -> bool { app.any_dialog_open() || with_host(app, |host, _| !host.is_empty()).unwrap_or(false) @@ -578,20 +583,42 @@ pub(crate) fn pump(app: &mut VectorcraftApp, _ctx: &egui::Context) { } None => {} } + answer_close(app, close); + if with_host(app, |host, _| host.get_mut::().is_some_and(|d| std::mem::take(&mut d.choose))).unwrap_or(false) { + choose(app); + } +} + +/// Takes the answer to the quit question given between two queued runs, before the next run +/// starts. True when it stopped the runs. +pub(crate) fn answer_close_between_runs(app: &mut VectorcraftApp) -> bool { + let Some(close) = with_host(app, |host, _| host.take::()).flatten() else { + return false; + }; + answer_close(app, Some(close)); + !app.session.script_running() +} + +/// With Stop as the answer to the quit question, stops the run, or between two queued runs, the +/// runs not yet started. +fn answer_close(app: &mut VectorcraftApp, close: Option::Result>>) { let startup = app.session.startup_script_running(); + // Between two queued runs: none runs, and the report is the last run's. + let between = app.session.script_running() && app.session.script_name().is_none(); if let Some(DialogResult::Ok(answer)) = close && answer.choice == PromptChoice::Proceed && app.session.script_abandon() { - let error = app.session.script_failure_text().unwrap_or_default(); - crate::script_runs::ended_with_error(app, startup, error); + if between { + crate::script_runs::stopped_between_runs(app); + } else { + let error = app.session.script_failure_text().unwrap_or_default(); + crate::script_runs::ended_with_error(app, startup, error); + } forget::(app); forget::(app); app.sync_views(); } - if with_host(app, |host, _| host.get_mut::().is_some_and(|d| std::mem::take(&mut d.choose))).unwrap_or(false) { - choose(app); - } } /// Gives the running script the answer of its dialog. Cancel is Cancel for a prompt, No for a diff --git a/crates/ui-egui/src/script_runs.rs b/crates/ui-egui/src/script_runs.rs index d9c9960ac0..1a17eb6974 100644 --- a/crates/ui-egui/src/script_runs.rs +++ b/crates/ui-egui/src/script_runs.rs @@ -18,6 +18,10 @@ pub fn poll(app: &mut VectorcraftApp) { if ask(app) { return; } + // Between two queued runs, the next one waits for the answer to the quit question. + if app.session.script_name().is_none() && (script_run::asking_to_close(app) || script_run::answer_close_between_runs(app)) { + return; + } let name = app.session.script_name().unwrap_or_default(); let startup = app.session.startup_script_running(); let Some(result) = app.session.script_pump() else { @@ -213,3 +217,18 @@ pub(crate) fn failed(app: &mut VectorcraftApp, error: String) { app.status(error); } } + +/// Shows that the runs `script.startup.run` queued were stopped between two of them, before the +/// next one started. The message shows first, before the round's notes ([`end_round`]). +pub(crate) fn stopped_between_runs(app: &mut VectorcraftApp) { + let message = "The scripts waiting to run were not run"; + let mut notes = vec![message.to_string()]; + notes.append(&mut app.ui.startup_notes); + if notes.len() == 1 { + // Notes an earlier round left for the same message are not this round's. + app.ui.status_notes = None; + app.status(message); + } else { + show_notes(app, notes); + } +} diff --git a/crates/ui-egui/src/tests/script_run.rs b/crates/ui-egui/src/tests/script_run.rs index f7e9a33f7b..5115693731 100644 --- a/crates/ui-egui/src/tests/script_run.rs +++ b/crates/ui-egui/src/tests/script_run.rs @@ -278,6 +278,63 @@ fn a_startup_script_stopped_by_quitting_stays_in_the_status_bar() { let _ = std::fs::remove_dir_all(&dir); } +#[test] +fn quitting_between_a_startup_script_and_the_chosen_script_stops_the_chosen_script() { + let mut app = app(); + let dir = folder("startup-quit-between"); + // A first startup script that cannot start leaves a note for the round. + std::fs::write(dir.join("0.jsx"), [0xff, 0xfe, 0x00]).unwrap(); + std::fs::write(dir.join("a.jsx"), "vc.log(1);").unwrap(); + app.session.attach_startup_scripts_dir(dir.clone()); + app.session.prefs.show_external_script_warning = false; + app.run("prefs.set", json!({"key": "runStartupScripts", "value": true})).unwrap(); + menus::run_ui_command(&mut app, "ui.runScript", &json!({ "source": DRAW, "name": "chosen" })).unwrap().unwrap(); + for _ in 0..10_000 { + if app.session.script_name().is_none() { + break; + } + script_runs::poll(&mut app); + } + assert!(app.session.script_running() && app.session.script_name().is_none(), "the chosen script waits for the next frame"); + script_run::ask_to_close(&mut app); + // Frames drawn while the question is open do not start the chosen script. + for _ in 0..3 { + script_runs::poll(&mut app); + } + assert!(app.session.script_running() && app.session.script_name().is_none(), "the chosen script waits for the answer"); + // A frame takes the answer before it would start the next run, then pumps the dialogs. + let id = open_id(&app, CLOSE_KIND); + assert!(script_run::with_host(&app, |host, ctx| host.confirm_by_id(ctx, id)).unwrap()); + script_runs::poll(&mut app); + assert!(!app.session.script_running()); + pump(&mut app); + script_runs::poll(&mut app); + let message = "The scripts waiting to run were not run"; + assert_eq!(app.ui.status, message); + let notes = app.ui.status_notes.clone().map(|(_, notes)| notes).unwrap_or_default(); + assert_eq!(notes.len(), 2, "{notes:?}"); + assert_eq!(notes[0], message); + assert!(notes[1].starts_with("0.jsx: "), "{notes:?}"); + assert_eq!(objects(&app), 0, "the chosen script did not run"); + // A later round stopped the same way, with no notes of its own, does not show the earlier round's. + std::fs::remove_file(dir.join("0.jsx")).unwrap(); + menus::run_ui_command(&mut app, "ui.runScript", &json!({ "source": DRAW, "name": "chosen" })).unwrap().unwrap(); + for _ in 0..10_000 { + if app.session.script_name().is_none() { + break; + } + script_runs::poll(&mut app); + } + assert!(app.session.script_running() && app.session.script_name().is_none()); + script_run::ask_to_close(&mut app); + assert!(confirm(&mut app, CLOSE_KIND)); + script_runs::poll(&mut app); + assert_eq!(app.ui.status, message); + assert_eq!(app.ui.status_notes, None); + assert_eq!(objects(&app), 0); + let _ = std::fs::remove_dir_all(&dir); +} + #[test] fn a_stop_names_the_files_the_run_left_written() { let mut app = app(); diff --git a/docs/mcp.md b/docs/mcp.md index 8311998f81..8950478cba 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -3310,7 +3310,8 @@ disabled, truncated, unreadable}`, with `then` holding `script.run`'s reply. In reply is `{reason, skipped: false, running, queued, failed, disabled, truncated, unreadable}`, with `failed` naming the runs that could not start before the first one did. Each run then reports as a `script.run` in the app does, the next one starts at the frame after, and a later run that cannot start, the chosen script included, is named in the -status bar. Stop (`script.stop`) asked for between two runs stops the run that starts next. Under `--automation-read-root` it reads the folder only when the folder lies inside a +status bar. Stop (`script.stop`) asked for between two runs stops the run that starts next. In the app, stopping the runs from +the prompt shown on quitting, between two runs, drops the runs not yet started, and the status bar says so. While that prompt is open, the next run does not start. Under `--automation-read-root` it reads the folder only when the folder lies inside a read root. With the preference on, `ui.runScript` and `ui.runInstalledScript` still return `script.run`'s reply, or its error when the chosen script cannot start, and add `startup` holding the `script.startup.run` reply. While a startup script runs before the chosen script, that reply is `{running: true, queued: true}`, and a chosen script that From 895fc362e82e909082d7356e2850086d5461563b Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 25 Nov 2026 17:58:58 -0800 Subject: [PATCH 090/151] JavaScript: a bound function inherits from its target's prototype With ECMAScript 2015, Function.prototype.bind gave every bound function Function.prototype as its prototype, so a bound generator function's constructor was Function instead of GeneratorFunction. The bound function now takes the target's prototype, read before length and name (ECMA-262 2020 section 9.4.1.3). Without the option it keeps Function.prototype, as ES5 section 15.3.4.5 specifies. --- crates/js/src/builtins.rs | 16 ++++++++++------ crates/js/src/generator_tests.rs | 7 +++++++ 2 files changed, 17 insertions(+), 6 deletions(-) diff --git a/crates/js/src/builtins.rs b/crates/js/src/builtins.rs index 1314a04a03..6757c79cb2 100644 --- a/crates/js/src/builtins.rs +++ b/crates/js/src/builtins.rs @@ -672,6 +672,10 @@ fn function_bind(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> J let Some(target) = this.as_object() else { return Err(interp.type_error("the value bind was called on is not a function")) }; let bound_this = arg(args, 0); let bound_args: Rc<[Value]> = args.get(1..).unwrap_or_default().into(); + // With ECMAScript 2015 the bound function inherits from the target's prototype, read before + // `length` and `name` (ECMA-262 2020 section 9.4.1.3 step 2), so a bound generator function + // inherits from %GeneratorFunction.prototype%. + let target_proto = interp.heap.object(target).and_then(|o| o.proto); // A host function's `length` is an ordinary property a script can set, so it is converted // to an integer first, as later editions specify. With ECMAScript 2015 only an own `length` is // read (ECMA-262 2020 section 19.2.3.2 step 4), so an inherited getter does not run. @@ -685,7 +689,7 @@ fn function_bind(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> J // Adding 0 turns a negative zero into 0. let length = (target_length - bound_args.len() as f64).max(0.0) + 0.0; if interp.options.es2015 { - return bind_es2015(interp, target, bound_this, bound_args, length); + return bind_es2015(interp, target, target_proto, bound_this, bound_args, length); } interp.reserve_heap(OBJECT_BYTES + prop_bytes(&["length", "caller", "arguments"]) + BOUND_ARG_BYTES * bound_args.len())?; let proto = interp.intrinsics.function_proto; @@ -707,9 +711,10 @@ fn prop_bytes(names: &[&str]) -> usize { /// The rest of `Function.prototype.bind` with [`crate::Options::es2015`] (ECMA-262 2020 section /// 19.2.3.2): the bound function's `length` is configurable, its `name` is `bound ` and the -/// target's `name` when that is a string (read after `length`, so a getter for it runs). It keeps -/// the `caller` and `arguments` that throw, as without the option. -fn bind_es2015(interp: &mut Interp, target: ObjId, bound_this: Value, bound_args: Rc<[Value]>, length: f64) -> JsResult { +/// target's `name` when that is a string (read after `length`, so a getter for it runs), and its +/// prototype is `proto`, the target's. It keeps the `caller` and `arguments` that throw, as +/// without the option. +fn bind_es2015(interp: &mut Interp, target: ObjId, proto: Option, bound_this: Value, bound_args: Rc<[Value]>, length: f64) -> JsResult { let target_name = match interp.get_from(target, &key("name"), &Value::Object(target))? { Value::String(s) => s, _ => Str::from(""), @@ -725,9 +730,8 @@ fn bind_es2015(interp: &mut Interp, target: ObjId, bound_this: Value, bound_args crate::string_builtins::charge_units(interp, name_len)?; let mut units: Vec = "bound ".encode_utf16().collect(); units.extend_from_slice(&target_units); - let proto = interp.intrinsics.function_proto; let class = Class::Function(Func::Bound { target, this: bound_this, args: bound_args.clone() }); - let f = interp.heap.alloc_object(Object::new(class, Some(proto))); + let f = interp.heap.alloc_object(Object::new(class, proto)); interp.heap.bytes = interp.heap.bytes.saturating_add(BOUND_ARG_BYTES * bound_args.len() + string_bytes(name_len)); interp.define(f, key("length"), Prop::Data { value: Value::Number(length), flags: CONFIGURABLE })?; interp.define(f, key("name"), Prop::Data { value: Value::String(Str::from_units(units)), flags: CONFIGURABLE })?; diff --git a/crates/js/src/generator_tests.rs b/crates/js/src/generator_tests.rs index 9c3ba3c139..e90943dbdd 100644 --- a/crates/js/src/generator_tests.rs +++ b/crates/js/src/generator_tests.rs @@ -184,6 +184,13 @@ fn generator_methods_and_the_generator_objects() { truth("function* g() {} g.prototype = 1; Object.getPrototypeOf(g()) === Object.getPrototypeOf(function* () {}).prototype"); } +#[test] +fn a_bound_generator_function_inherits_from_the_targets_prototype() { + truth("function* g() {} var b = g.bind(null); Object.getPrototypeOf(b) === Object.getPrototypeOf(g) && b.constructor !== Function"); + truth("function* g(a) { yield a; } g.bind(null, 3)().next().value === 3"); + truth("function f() {} Object.getPrototypeOf(f.bind(null)) === Function.prototype"); +} + #[test] fn yield_is_an_identifier_outside_generators_in_sloppy_code() { truth("var yield = 1; yield + 1 === 2"); From 280cef492e825c439f5c4d48a03de25f584216b6 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 25 Nov 2026 18:11:56 -0800 Subject: [PATCH 091/151] Retype: keep faces read for split shapes only The installed-font search keeps a face that holds glyphs without completing a shape only while a split shape is not found yet, and drops the kept faces once every split shape is found. A shape matched whole is compared without the kept faces. --- crates/engine/src/cmd/retype_installed.rs | 23 ++++++++++++++++--- .../engine/src/cmd/retype_installed_tests.rs | 15 ++++++++++++ 2 files changed, 35 insertions(+), 3 deletions(-) diff --git a/crates/engine/src/cmd/retype_installed.rs b/crates/engine/src/cmd/retype_installed.rs index a113982379..4c3aeff0b9 100644 --- a/crates/engine/src/cmd/retype_installed.rs +++ b/crates/engine/src/cmd/retype_installed.rs @@ -264,6 +264,8 @@ fn search_sought( } files.sort_by(|a, b| a.1.cmp(&b.1).then_with(|| a.0.cmp(&b.0))); let mut matched = vec![false; shapes.len()]; + // Is a split shape not found yet: only then are faces kept in `partial`. + let open = |matched: &[bool]| shapes.iter().zip(matched).any(|(s, m)| !*m && !s.groups.is_empty()); let (mut bytes_left, mut glyphs_left) = (limits.read, limits.glyphs); let total = files.len() as u64; for (i, (path, len, styles)) in files.iter().enumerate() { @@ -313,6 +315,8 @@ fn search_sought( if matched.get(k).copied().unwrap_or(true) { return vec![]; } + // A shape matched whole only takes one glyph: the faces read before it do not hold it. + let extra = if s.groups.is_empty() { &[] } else { extra }; let with: Vec<&RetypeIndex> = beside.iter().copied().chain(&found).chain(extra.iter().copied()).chain(std::iter::once(ix)).collect(); super::shape_parts(s.path, s.groups, s.fill, s.once, &with, tolerance) }; @@ -324,9 +328,12 @@ fn search_sought( (0..shapes.len()).map(|k| (k, parts_with(&parts, &index, k))).filter(|(_, p)| !p.is_empty()).collect(); let fits: Vec = first.iter().map(|(k, _)| *k).collect(); if fits.is_empty() { - // The face holds glyphs of a shape without completing one: a later face may. - // The latest are kept: the oldest goes when the cap is reached. - if !every { + // The face holds glyphs of a shape without completing one: a later face may, while + // a split shape is not found. The latest are kept: the oldest goes when the cap is + // reached. + if !every && open(&matched) { + #[cfg(test)] + KEPT_PARTIAL.with(|n| n.set(n.get() + 1)); if partial.len() >= MAX_FACES { partial.remove(0); } @@ -407,6 +414,10 @@ fn search_sought( if !every && matched.iter().all(|m| *m) { return Ok(out); } + // With every split shape found, the faces kept for them are dropped. + if !open(&matched) { + partial.clear(); + } } // The cap reached with the file's last face: the later files are not compared. if out.faces.len() >= limits.faces { @@ -417,6 +428,12 @@ fn search_sought( Ok(out) } +#[cfg(test)] +thread_local! { + /// How many times a search on this thread kept a face it read in `partial`. + static KEPT_PARTIAL: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + /// For each of `parts` (each part's candidates) that none of the faces of `held` has a glyph of, /// one face that does: a loaded face of `beside` (the command compares it with the face found), /// or else a face of `partial`, read before. The places in `partial` of those, in order, and the diff --git a/crates/engine/src/cmd/retype_installed_tests.rs b/crates/engine/src/cmd/retype_installed_tests.rs index 53c7a6bd04..4945d9c259 100644 --- a/crates/engine/src/cmd/retype_installed_tests.rs +++ b/crates/engine/src/cmd/retype_installed_tests.rs @@ -180,6 +180,21 @@ fn the_search_stops_once_every_shape_matches_unless_every_face_is_wanted() { assert_eq!(families, ["Retype Copy E", "Retype Copy F"]); } +#[test] +fn faces_read_are_kept_for_split_shapes_only() { + let (db, _) = installed("kept-whole", &["Retype Kept Whole A", "Retype Kept Whole B", "Retype Kept Whole C"]); + // The k matches in the first file and the circle in none, so every file is read; the later + // files hold the k's glyph without completing a shape. With every shape whole, none is kept. + let mut shapes = glyphs(&db, "k"); + shapes.push(kurbo::Circle::new((300.0, 100.0), 7.3).to_path(0.1)); + assert!(shape_key(&shapes[1]).is_some(), "the circle has a key to look glyphs up by"); + let refs: Vec<&BezPath> = shapes.iter().collect(); + super::KEPT_PARTIAL.with(|n| n.set(0)); + let found = search(&db, &refs, false).unwrap(); + assert_eq!((found.read, found.faces.len()), (3, 1)); + assert_eq!(super::KEPT_PARTIAL.with(std::cell::Cell::get), 0, "no face read is kept"); +} + #[test] fn faces_past_the_limits_are_skipped_and_counted() { let (db, files) = installed("limits", &["Retype Copy G", "Retype Copy H"]); From e68e05fc827c32f329f68ace5732f86dfb397acb Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 25 Nov 2026 18:39:55 -0800 Subject: [PATCH 092/151] i18n: Retype messages are added in English only The rows this branch added to the 25 catalogs are removed; translations go through storytold/craft-i18n. The Retype run tests draw the progress window and settle the context with testing::ui_context and part_frame. --- crates/ui-egui/src/i18n/ca.tsv | 3 --- crates/ui-egui/src/i18n/cs.tsv | 3 --- crates/ui-egui/src/i18n/da.tsv | 3 --- crates/ui-egui/src/i18n/de.tsv | 3 --- crates/ui-egui/src/i18n/el.tsv | 3 --- crates/ui-egui/src/i18n/es.tsv | 3 --- crates/ui-egui/src/i18n/fi.tsv | 3 --- crates/ui-egui/src/i18n/fr.tsv | 3 --- crates/ui-egui/src/i18n/hi.tsv | 3 --- crates/ui-egui/src/i18n/hu.tsv | 3 --- crates/ui-egui/src/i18n/id.tsv | 3 --- crates/ui-egui/src/i18n/it.tsv | 3 --- crates/ui-egui/src/i18n/ja.tsv | 3 --- crates/ui-egui/src/i18n/ka.tsv | 3 --- crates/ui-egui/src/i18n/ko.tsv | 3 --- crates/ui-egui/src/i18n/nl.tsv | 3 --- crates/ui-egui/src/i18n/pl.tsv | 3 --- crates/ui-egui/src/i18n/pt-br.tsv | 3 --- crates/ui-egui/src/i18n/ru.tsv | 3 --- crates/ui-egui/src/i18n/sv.tsv | 3 --- crates/ui-egui/src/i18n/tr.tsv | 3 --- crates/ui-egui/src/i18n/uk.tsv | 3 --- crates/ui-egui/src/i18n/vi.tsv | 3 --- crates/ui-egui/src/i18n/zh-hans.tsv | 3 --- crates/ui-egui/src/i18n/zh-hant.tsv | 3 --- crates/ui-egui/src/tests/retype_runs.rs | 11 ++++------- 26 files changed, 4 insertions(+), 82 deletions(-) diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index e059c50b20..1e152091b2 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -1888,7 +1888,6 @@ digits Malayalam Malaiàlam Reset Retype Panel Restableix el panell Torna a escriure List Matching Fonts Llista els tipus de lletra coincidents Retype Preview Previsualització del panell Torna a escriure -@msg `installed` must be true, false or null `installed` ha de ser true, false o null @msg `count` must be a whole number from 1 to 96 `count` ha de ser un nombre enter entre 1 i 96 @msg `size` must be small, medium or large `size` ha de ser small, medium o large @msg `text` must be a string of at most 100 characters `text` ha de ser una cadena de 100 caràcters com a màxim @@ -7663,8 +7662,6 @@ variable-list-end {0}, {1} {0} i {1} @msg {_1} files {_1} fitxers @msg {_1} files are written by file.saveAsTemplate els fitxers {_1} els escriu file.saveAsTemplate @msg {_1} files can be opened but not written (see document.formats) els fitxers {_1} es poden obrir però no escriure (consulta document.formats) -@msg Retype failed: internal error: its thread stopped (please report this bug) Torna a escriure ha fallat: error intern: el seu fil s'ha aturat (informeu d'aquest error) -@msg Retype finished, but the document or its selection changed meanwhile: run it again Torna a escriure ha acabat, però el document o la seva selecció ha canviat mentrestant: torna-ho a executar @msg {_1} finished, but the document or the plug-in changed meanwhile: run it again {_1} ha acabat, però el document o el complement ha canviat mentrestant: torna-ho a executar @msg {_1} font families available {_1} famílies de tipus de lletra disponibles @msg {_1} has no {_2} style {_1} no té cap estil {_2} diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index 3c306853b3..8da0ceca13 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -464,7 +464,6 @@ Reset Retype Panel Obnovit panel Přepsat List Matching Fonts Vypsat odpovídající písma Retype Preview Náhled v panelu Přepsat -@msg `installed` must be true, false or null `installed` musí být true, false nebo null @msg `count` must be a whole number from 1 to 96 `count` musí být celé číslo od 1 do 96 @msg `size` must be small, medium or large `size` musí být small, medium nebo large @msg `text` must be a string of at most 100 characters `text` musí být řetězec o nejvýše 100 znacích @@ -8979,8 +8978,6 @@ breakText Glyphs Glyfy @msg Image Trace failed: internal error: its thread stopped (please report this bug) Vektorizace obrazu selhala: vnitřní chyba: její vlákno se zastavilo (nahlaste prosím tuto chybu) @msg Image Trace failed: {e} Vektorizace obrazu selhala: {e} @msg Image Trace finished, but its document was closed Vektorizace obrazu skončila, ale její dokument byl zavřen -@msg Retype failed: internal error: its thread stopped (please report this bug) Přepsání selhalo: vnitřní chyba: jeho vlákno se zastavilo (nahlaste prosím tuto chybu) -@msg Retype finished, but the document or its selection changed meanwhile: run it again Přepsání skončilo, ale dokument nebo jeho výběr se mezitím změnil: spusťte ho znovu @msg Image Trace finished, but the image or its settings changed meanwhile: trace it again Vektorizace obrazu skončila, ale obraz nebo jeho nastavení se mezitím změnily: vektorizujte ho znovu @msg Image Trace finished, but its document was reverted: trace it again Vektorizace obrazu skončila, ale její dokument byl vrácen k uložené verzi: vektorizujte ho znovu @msg Import SVG Filter reads SVG files, not SVGZ Importovat filtr SVG čte soubory SVG, ne SVGZ diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index 054f36a584..34e2a28984 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -1035,8 +1035,6 @@ liquify-list-end {0}, {1} {0} og {1} @msg Image Trace failed: {e} Billedsporing mislykkedes: {e} @msg Image Trace finished, but its document was closed Billedsporing blev færdig, men dens dokument blev lukket @msg Image Trace finished, but its document was reverted: trace it again Billedsporing blev færdig, men dens dokument blev gendannet: spor det igen -@msg Retype failed: internal error: its thread stopped (please report this bug) Genindtast mislykkedes: intern fejl: dens tråd stoppede (rapportér venligst denne fejl) -@msg Retype finished, but the document or its selection changed meanwhile: run it again Genindtast blev færdig, men dokumentet eller dets markering ændrede sig imens: kør det igen @msg Image Trace finished, but the image or its settings changed meanwhile: trace it again Billedsporing blev færdig, men billedet eller dets indstillinger ændrede sig imens: spor det igen @msg Import SVG Filter reads SVG files, not SVGZ Importér SVG-filter læser SVG-filer, ikke SVGZ @msg Invalid dimension offset Ugyldig forskydning af målet @@ -3213,7 +3211,6 @@ liquify-list-end {0}, {1} {0} og {1} Reset Retype Panel Nulstil panelet Genindtast List Matching Fonts Vis matchende skrifttyper Retype Preview Forhåndsvisning i panelet Genindtast -@msg `installed` must be true, false or null `installed` skal være true, false eller null @msg `count` must be a whole number from 1 to 96 `count` skal være et heltal fra 1 til 96 @msg `size` must be small, medium or large `size` skal være small, medium eller large @msg `text` must be a string of at most 100 characters `text` skal være en streng på højst 100 tegn diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index ee68d8b335..3810951d8d 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -1385,7 +1385,6 @@ font-technology Variable Variabel Reset Retype Panel Bedienfeld „Neu setzen“ zurücksetzen List Matching Fonts Passende Schriften auflisten Retype Preview Vorschau im Bedienfeld „Neu setzen“ -@msg `installed` must be true, false or null `installed` muss true, false oder null sein @msg `count` must be a whole number from 1 to 96 `count` muss eine ganze Zahl von 1 bis 96 sein @msg `size` must be small, medium or large `size` muss small, medium oder large sein @msg `text` must be a string of at most 100 characters `text` muss eine Zeichenfolge mit höchstens 100 Zeichen sein @@ -8863,8 +8862,6 @@ breakText Glyphs Glyphen @msg Image Trace failed: internal error: its thread stopped (please report this bug) Bildnachzeichner fehlgeschlagen: interner Fehler: Sein Thread wurde beendet (bitte melden Sie diesen Fehler) @msg Image Trace failed: {e} Bildnachzeichner fehlgeschlagen: {e} @msg Image Trace finished, but its document was closed Bildnachzeichner abgeschlossen, aber sein Dokument wurde geschlossen -@msg Retype failed: internal error: its thread stopped (please report this bug) Neu setzen fehlgeschlagen: interner Fehler: Sein Thread wurde beendet (bitte melden Sie diesen Fehler) -@msg Retype finished, but the document or its selection changed meanwhile: run it again Neu setzen abgeschlossen, aber das Dokument oder seine Auswahl hat sich inzwischen geändert: Führen Sie es erneut aus @msg Image Trace finished, but the image or its settings changed meanwhile: trace it again Bildnachzeichner abgeschlossen, aber das Bild oder seine Einstellungen haben sich inzwischen geändert: Zeichnen Sie es erneut nach @msg Image Trace finished, but its document was reverted: trace it again Bildnachzeichner abgeschlossen, aber sein Dokument wurde auf die letzte Version zurückgesetzt: Zeichnen Sie es erneut nach @msg Invalid dimension offset Ungültiger Bemaßungsversatz diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index 1b82a6dcc0..bea601b6ec 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -1329,7 +1329,6 @@ font-technology Variable Μεταβλητές Reset Retype Panel Επαναφορά πίνακα Επαναπληκτρολόγησης List Matching Fonts Λίστα αντίστοιχων γραμματοσειρών Retype Preview Προεπισκόπηση πίνακα Επαναπληκτρολόγησης -@msg `installed` must be true, false or null Το `installed` πρέπει να είναι true, false ή null @msg `count` must be a whole number from 1 to 96 Το `count` πρέπει να είναι ακέραιος από 1 έως 96 @msg `size` must be small, medium or large Το `size` πρέπει να είναι small, medium ή large @msg `text` must be a string of at most 100 characters Το `text` πρέπει να είναι συμβολοσειρά έως 100 χαρακτήρων @@ -7302,8 +7301,6 @@ axis Y Axis Άξονας Y The plug-in is computing… Το πρόσθετο υπολογίζει… Inspect Plug-in Επιθεώρηση προσθέτου Cancel Plug-in Run Ακύρωση εκτέλεσης προσθέτου -@msg Retype failed: internal error: its thread stopped (please report this bug) Η Επαναπληκτρολόγηση απέτυχε: εσωτερικό σφάλμα: το νήμα της σταμάτησε (αναφέρετε αυτό το σφάλμα) -@msg Retype finished, but the document or its selection changed meanwhile: run it again Η Επαναπληκτρολόγηση ολοκληρώθηκε, αλλά το έγγραφο ή η επιλογή του άλλαξε στο μεταξύ: εκτελέστε την ξανά @msg {_1} finished, but the document or the plug-in changed meanwhile: run it again Το {_1} ολοκληρώθηκε, αλλά το έγγραφο ή το πρόσθετο άλλαξε στο μεταξύ: εκτελέστε το ξανά @msg Running “{name}”… Εκτέλεση του «{name}»… @msg a live effect runs while the document is drawn, so it can't be `heavy` ένα δυναμικό εφέ εκτελείται κατά τη σχεδίαση του εγγράφου, οπότε δεν μπορεί να είναι `heavy` diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index d60f9cb0ef..c3583a807a 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -1409,7 +1409,6 @@ font-technology Variable Variables Reset Retype Panel Restablecer panel Reescribir List Matching Fonts Enumerar fuentes coincidentes Retype Preview Vista previa del panel Reescribir -@msg `installed` must be true, false or null `installed` debe ser true, false o null @msg `count` must be a whole number from 1 to 96 `count` debe ser un número entero entre 1 y 96 @msg `size` must be small, medium or large `size` debe ser small, medium o large @msg `text` must be a string of at most 100 characters `text` debe ser una cadena de 100 caracteres como máximo @@ -9317,8 +9316,6 @@ breakText Glyphs Glifos @msg Image Trace failed: internal error: its thread stopped (please report this bug) Error de Calco de imagen: error interno: su hilo se detuvo (informa de este error) @msg Image Trace failed: {e} Error de Calco de imagen: {e} @msg Image Trace finished, but its document was closed Calco de imagen terminó, pero su documento se cerró -@msg Retype failed: internal error: its thread stopped (please report this bug) Error de Reescribir: error interno: su hilo se detuvo (informa de este error) -@msg Retype finished, but the document or its selection changed meanwhile: run it again Reescribir terminó, pero el documento o su selección cambiaron mientras tanto: ejecútalo de nuevo @msg Image Trace finished, but the image or its settings changed meanwhile: trace it again Calco de imagen terminó, pero la imagen o sus ajustes cambiaron mientras tanto: cálcala de nuevo @msg Invalid dimension offset Desplazamiento de cota no válido @msg Invalid point Punto no válido diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index 36fee034f4..52be55651e 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -461,7 +461,6 @@ Reset Retype Panel Palauta Kirjoita uudelleen -paneeli List Matching Fonts Luettele vastaavat fontit Retype Preview Kirjoita uudelleen -paneelin esikatselu -@msg `installed` must be true, false or null `installed` on oltava true, false tai null @msg `count` must be a whole number from 1 to 96 `count` on oltava kokonaisluku 1–96 @msg `size` must be small, medium or large `size` on oltava small, medium tai large @msg `text` must be a string of at most 100 characters `text` on oltava enintään 100 merkin merkkijono @@ -7379,8 +7378,6 @@ axis Y Axis Y-akseli The plug-in is computing… Laajennus laskee… Inspect Plug-in Tarkastele laajennusta Cancel Plug-in Run Peruuta laajennuksen ajo -@msg Retype failed: internal error: its thread stopped (please report this bug) Kirjoita uudelleen epäonnistui: sisäinen virhe: sen säie pysähtyi (ilmoita tästä virheestä) -@msg Retype finished, but the document or its selection changed meanwhile: run it again Kirjoita uudelleen valmistui, mutta asiakirja tai sen valinta muuttui sillä välin: suorita se uudelleen @msg {_1} finished, but the document or the plug-in changed meanwhile: run it again {_1} valmistui, mutta asiakirja tai laajennus muuttui sillä välin: suorita se uudelleen @msg Running “{name}”… Suoritetaan ”{name}”… @msg a live effect runs while the document is drawn, so it can't be `heavy` live-tehoste suoritetaan asiakirjaa piirrettäessä, joten se ei voi olla `heavy` diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 88a2499ac7..b1c56002d2 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -1399,7 +1399,6 @@ font-technology Variable Variables Reset Retype Panel Réinitialiser le panneau Retaper List Matching Fonts Lister les polices correspondantes Retype Preview Aperçu du panneau Retaper -@msg `installed` must be true, false or null `installed` doit valoir true, false ou null @msg `count` must be a whole number from 1 to 96 `count` doit être un nombre entier compris entre 1 et 96 @msg `size` must be small, medium or large `size` doit valoir small, medium ou large @msg `text` must be a string of at most 100 characters `text` doit être une chaîne d’au plus 100 caractères @@ -8848,8 +8847,6 @@ breakText Glyphs Glyphes @msg Image Trace failed: {e} Échec de la vectorisation de l’image : {e} @msg Image Trace finished, but its document was closed La vectorisation de l’image est terminée, mais son document a été fermé @msg Image Trace finished, but its document was reverted: trace it again La vectorisation de l’image est terminée, mais son document a été rétabli à la version précédente : vectorisez-la à nouveau -@msg Retype failed: internal error: its thread stopped (please report this bug) Échec de Retaper. Erreur interne. Son thread s’est arrêté (merci de signaler ce bogue) -@msg Retype finished, but the document or its selection changed meanwhile: run it again Retaper est terminé, mais le document ou sa sélection a changé entre-temps. Relancez-le @msg Image Trace finished, but the image or its settings changed meanwhile: trace it again La vectorisation de l’image est terminée, mais l’image ou ses réglages ont changé entre-temps : vectorisez-la à nouveau @msg Import SVG Filter reads SVG files, not SVGZ Importer un filtre SVG lit les fichiers SVG, pas SVGZ @msg Invalid dimension offset Décalage de cote non valide diff --git a/crates/ui-egui/src/i18n/hi.tsv b/crates/ui-egui/src/i18n/hi.tsv index a478b74785..8bf19ba7e7 100644 --- a/crates/ui-egui/src/i18n/hi.tsv +++ b/crates/ui-egui/src/i18n/hi.tsv @@ -2335,7 +2335,6 @@ arrowhead Feather पंख Reset Retype Panel फिर से टाइप करें पैनल रीसेट करें List Matching Fonts मिलते-जुलते फ़ॉन्ट की सूची Retype Preview फिर से टाइप करें पैनल का प्रीव्यू -@msg `installed` must be true, false or null `installed` को true, false या null होना चाहिए @msg `count` must be a whole number from 1 to 96 `count` 1 से 96 तक पूरी संख्या होना चाहिए @msg `size` must be small, medium or large `size` को small, medium या large होना चाहिए @msg `text` must be a string of at most 100 characters `text` अधिकतम 100 वर्णों की स्ट्रिंग होनी चाहिए @@ -8094,8 +8093,6 @@ liquify-list-end {0}, {1} {0} और {1} @msg Image Trace failed: {e} इमेज ट्रेस विफल: {e} @msg Image Trace failed: internal error: its thread stopped (please report this bug) इमेज ट्रेस विफल: आंतरिक त्रुटि: इसके धागे को बंद कर दिया (कृपया इस बग की रिपोर्ट करें) @msg Image Trace finished, but its document was closed इमेज ट्रेस समाप्त हो गया, लेकिन इसका डॉक्यूमेंट बंद हो गया। -@msg Retype failed: internal error: its thread stopped (please report this bug) फिर से टाइप करना विफल: आंतरिक त्रुटि: इसका थ्रेड रुक गया (कृपया इस बग की रिपोर्ट करें) -@msg Retype finished, but the document or its selection changed meanwhile: run it again फिर से टाइप करना समाप्त हो गया, लेकिन इस बीच दस्तावेज़ या उसका चयन बदल गया: इसे फिर से चलाएँ @msg Image Trace finished, but the image or its settings changed meanwhile: trace it again इमेज ट्रेस समाप्त हो गया, लेकिन इस बीच इमेज या इसकी सेटिंग्स बदल गई: इसे फिर से ट्रेस करें @msg Image Trace finished, but its document was reverted: trace it again इमेज ट्रेस समाप्त हो गया, लेकिन इसके डॉक्यूमेंट को मूल स्थिति में लाया गया: इसे फिर से ट्रेस करें @msg Image Trace: the traced image is missing इमेज ट्रेस: ज्ञात इमेज गायब है diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index dbcc2015ab..273609ed89 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -1744,7 +1744,6 @@ digits Malayalam Malajálam Reset Retype Panel Újragépelés panel visszaállítása List Matching Fonts Egyező betűtípusok listázása Retype Preview Újragépelés panel előnézete -@msg `installed` must be true, false or null `installed`: true, false vagy null kell @msg `count` must be a whole number from 1 to 96 `count`: 1 és 96 közötti egész szám kell @msg `size` must be small, medium or large `size`: small, medium vagy large kell @msg `text` must be a string of at most 100 characters `text`: legfeljebb 100 karakteres karakterlánc kell @@ -8850,8 +8849,6 @@ breakText Glyphs Glifák @msg Image Trace failed: internal error: its thread stopped (please report this bug) A képvektorizálás nem sikerült: belső hiba: a szála leállt (kérjük, jelentsd ezt a hibát) @msg Image Trace failed: {e} A képvektorizálás nem sikerült: {e} @msg Image Trace finished, but its document was closed A képvektorizálás elkészült, de a dokumentumát bezárták -@msg Retype failed: internal error: its thread stopped (please report this bug) Az újragépelés nem sikerült: belső hiba: a szála leállt (kérjük, jelentsd ezt a hibát) -@msg Retype finished, but the document or its selection changed meanwhile: run it again Az újragépelés elkészült, de a dokumentum vagy a kijelölése közben megváltozott: futtasd újra @msg Image Trace finished, but the image or its settings changed meanwhile: trace it again A képvektorizálás elkészült, de a kép vagy a beállításai közben megváltoztak: vektorizáld újra @msg Image Trace finished, but its document was reverted: trace it again A képvektorizálás elkészült, de a dokumentumát visszaállították a mentett változatra: vektorizáld újra @msg Import SVG Filter reads SVG files, not SVGZ Az SVG-szűrő importálása SVG-fájlokat olvas, SVGZ-fájlokat nem diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index b9ab4bd9c4..3192fc4476 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -411,8 +411,6 @@ @msg `spread` must be pad, repeat or reflect `spread` harus pad, repeat atau reflect @msg `repeats` must be a whole number from 1 to {MAX_REPEATS} `repeats` harus berupa bilangan bulat dari 1 sampai {MAX_REPEATS} @msg `spread` applies to linear, radial, conic and diamond gradients `spread` berlaku untuk gradien linear, radial, conic, dan diamond -@msg Retype failed: internal error: its thread stopped (please report this bug) Ketik Ulang gagal: kesalahan internal: utasnya berhenti (harap laporkan bug ini) -@msg Retype finished, but the document or its selection changed meanwhile: run it again Ketik Ulang selesai, tetapi dokumen atau pilihannya berubah sementara itu: jalankan lagi @msg {_1} finished, but the document or the plug-in changed meanwhile: run it again {_1} selesai, tetapi dokumen atau plug-in berubah sementara itu: jalankan lagi @msg Running “{name}”… Menjalankan “{name}”… @msg a live effect runs while the document is drawn, so it can't be `heavy` efek langsung berjalan saat dokumen digambar, sehingga tidak dapat `heavy` @@ -1088,7 +1086,6 @@ Reset Retype Panel Setel ulang panel Ketik Ulang List Matching Fonts Daftar font yang cocok Retype Preview Pratinjau panel Ketik Ulang -@msg `installed` must be true, false or null `installed` harus true, false, atau null @msg `count` must be a whole number from 1 to 96 `count` harus bilangan bulat dari 1 sampai 96 @msg `size` must be small, medium or large `size` harus small, medium, atau large @msg `text` must be a string of at most 100 characters `text` harus string dengan paling banyak 100 karakter diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index 7a42c2f922..8e8d1abb62 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -1422,7 +1422,6 @@ font-technology Variable Variabili Reset Retype Panel Reimposta pannello Ridigita List Matching Fonts Elenca font corrispondenti Retype Preview Anteprima del pannello Ridigita -@msg `installed` must be true, false or null `installed` deve essere true, false o null @msg `count` must be a whole number from 1 to 96 `count` deve essere un numero intero compreso tra 1 e 96 @msg `size` must be small, medium or large `size` deve essere small, medium o large @msg `text` must be a string of at most 100 characters `text` deve essere una stringa di al massimo 100 caratteri @@ -8916,8 +8915,6 @@ breakText Glyphs Glifi @msg Image Trace failed: internal error: its thread stopped (please report this bug) Ricalco immagine non riuscito: errore interno: il suo thread si è fermato (segnala questo bug) @msg Image Trace failed: {e} Ricalco immagine non riuscito: {e} @msg Image Trace finished, but its document was closed Ricalco immagine terminato, ma il suo documento è stato chiuso -@msg Retype failed: internal error: its thread stopped (please report this bug) Ridigita non riuscito: errore interno: il suo thread si è fermato (segnala questo bug) -@msg Retype finished, but the document or its selection changed meanwhile: run it again Ridigita terminato, ma nel frattempo il documento o la sua selezione sono cambiati: eseguilo di nuovo @msg Image Trace finished, but the image or its settings changed meanwhile: trace it again Ricalco immagine terminato, ma nel frattempo l'immagine o le sue impostazioni sono cambiate: ricalcala di nuovo @msg Image Trace finished, but its document was reverted: trace it again Ricalco immagine terminato, ma il suo documento è stato ripristinato: ricalcala di nuovo @msg Invalid dimension offset Distanza della quota non valida diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index f756f14c0d..1dc697d1d3 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -525,7 +525,6 @@ digits Malayalam マラヤーラム数字 Reset Retype Panel リタイプパネルをリセット List Matching Fonts 一致するフォントの一覧 Retype Preview リタイプパネルのプレビュー -@msg `installed` must be true, false or null `installed` には true、false または null を指定してください @msg `count` must be a whole number from 1 to 96 `count` には 1 から 96 の整数を指定してください @msg `size` must be small, medium or large `size` には small、medium、large のいずれかを指定してください @msg `text` must be a string of at most 100 characters `text` には 100 文字以内の文字列を指定してください @@ -7733,8 +7732,6 @@ axis Y Axis Y 軸 @msg Image Trace failed: internal error: its thread stopped (please report this bug) 画像トレースに失敗しました: 内部エラー: スレッドが停止しました (このバグを報告してください) @msg Image Trace failed: {e} 画像トレースに失敗しました: {e} @msg Image Trace finished, but its document was closed 画像トレースは完了しましたが、ドキュメントが閉じられています -@msg Retype failed: internal error: its thread stopped (please report this bug) リタイプに失敗しました: 内部エラー: スレッドが停止しました (このバグを報告してください) -@msg Retype finished, but the document or its selection changed meanwhile: run it again リタイプは完了しましたが、その間にドキュメントまたは選択範囲が変更されました: もう一度実行してください @msg Image Trace finished, but the image or its settings changed meanwhile: trace it again 画像トレースは完了しましたが、その間に画像または設定が変更されました: もう一度トレースしてください @msg Image Trace finished, but its document was reverted: trace it again 画像トレースは完了しましたが、ドキュメントは保存済みの状態に戻されました: もう一度トレースしてください @msg Invalid dimension offset 寸法のオフセットが無効です diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index c26a3e6f0d..d53fa5c3b1 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -90,8 +90,6 @@ @msg Image Trace failed: internal error: its thread stopped (please report this bug) გამოსახულების ვექტორიზაცია ვერ მოხერხდა: შიდა შეცდომა: მისი ნაკადი შეჩერდა (გთხოვთ, შეგვატყობინოთ ამ ხარვეზის შესახებ) @msg Image Trace failed: {e} გამოსახულების ვექტორიზაცია ვერ მოხერხდა: {e} @msg Image Trace finished, but its document was closed გამოსახულების ვექტორიზაცია დასრულდა, მაგრამ მისი დოკუმენტი დაიხურა -@msg Retype failed: internal error: its thread stopped (please report this bug) ხელახლა აკრეფა ვერ მოხერხდა: შიდა შეცდომა: მისი ნაკადი შეჩერდა (გთხოვთ, შეგვატყობინოთ ამ ხარვეზის შესახებ) -@msg Retype finished, but the document or its selection changed meanwhile: run it again ხელახლა აკრეფა დასრულდა, მაგრამ ამასობაში დოკუმენტი ან მისი მონიშვნა შეიცვალა: გაუშვით ხელახლა @msg Image Trace finished, but the image or its settings changed meanwhile: trace it again გამოსახულების ვექტორიზაცია დასრულდა, მაგრამ ამასობაში გამოსახულება ან მისი პარამეტრები შეიცვალა: გაუშვით ვექტორიზაცია ხელახლა @msg Import SVG Filter reads SVG files, not SVGZ „SVG ფილტრის იმპორტი“ კითხულობს SVG ფაილებს და არა SVGZ-ს @msg Invalid dimension offset ზომის არასწორი წანაცვლება @@ -2598,7 +2596,6 @@ Reset Retype Panel ხელახლა აკრეფის პანელის ჩამოყრა List Matching Fonts შესაბამისი შრიფტების სია Retype Preview ხელახლა აკრეფის პანელის წინასწარი ნახვა -@msg `installed` must be true, false or null `installed` უნდა იყოს true, false ან null @msg `count` must be a whole number from 1 to 96 `count` უნდა იყოს მთელი რიცხვი 1-დან 96-მდე @msg `size` must be small, medium or large `size` უნდა იყოს small, medium ან large @msg `text` must be a string of at most 100 characters `text` უნდა იყოს არაუმეტეს 100 სიმბოლოს სტრიქონი diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index 047ba957d4..113e5f0147 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -518,7 +518,6 @@ digits Malayalam 말라얄람어 Reset Retype Panel 리타입 패널 재설정 List Matching Fonts 일치하는 글꼴 목록 Retype Preview 리타입 패널 미리 보기 -@msg `installed` must be true, false or null `installed`은(는) true, false 또는 null이어야 합니다 @msg `count` must be a whole number from 1 to 96 `count`는 1에서 96 사이의 정수여야 합니다 @msg `size` must be small, medium or large `size`는 small, medium 또는 large여야 합니다 @msg `text` must be a string of at most 100 characters `text`는 최대 100자의 문자열이어야 합니다 @@ -8618,8 +8617,6 @@ breakText Glyphs 글리프 @msg Image Trace failed: internal error: its thread stopped (please report this bug) 이미지 추적 실패: 내부 오류: 스레드가 멈췄습니다(이 버그를 보고해 주세요) @msg Image Trace failed: {e} 이미지 추적 실패: {e} @msg Image Trace finished, but its document was closed 이미지 추적이 끝났지만 문서가 닫혔습니다 -@msg Retype failed: internal error: its thread stopped (please report this bug) 리타입 실패: 내부 오류: 스레드가 멈췄습니다(이 버그를 보고해 주세요) -@msg Retype finished, but the document or its selection changed meanwhile: run it again 리타입이 끝났지만 그 사이에 문서나 선택 영역이 바뀌었습니다: 다시 실행하세요 @msg Image Trace finished, but the image or its settings changed meanwhile: trace it again 이미지 추적이 끝났지만 그 사이에 이미지나 설정이 바뀌었습니다: 다시 추적하세요 @msg Image Trace finished, but its document was reverted: trace it again 이미지 추적이 끝났지만 문서가 되돌려졌습니다: 다시 추적하세요 @msg Import SVG Filter reads SVG files, not SVGZ SVG 필터 가져오기는 SVGZ가 아닌 SVG 파일을 읽습니다 diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index 80b000fd20..414d7f2982 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -1072,7 +1072,6 @@ liquify-list-end {0}, {1} {0} en {1} Reset Retype Panel Paneel Opnieuw typen herstellen List Matching Fonts Overeenkomende lettertypen weergeven Retype Preview Voorbeeld in paneel Opnieuw typen -@msg `installed` must be true, false or null `installed` moet true, false of null zijn @msg `count` must be a whole number from 1 to 96 `count` moet een geheel getal van 1 tot 96 zijn @msg `size` must be small, medium or large `size` moet small, medium of large zijn @msg `text` must be a string of at most 100 characters `text` moet een tekenreeks van hoogstens 100 tekens zijn @@ -6481,8 +6480,6 @@ imageTrace Outline Contour @msg Image Trace failed: internal error: its thread stopped (please report this bug) Afbeelding traceren is mislukt: interne fout: de thread ervan is gestopt (meld deze bug alsjeblieft) @msg Image Trace failed: {e} Afbeelding traceren is mislukt: {e} @msg Image Trace finished, but its document was closed Afbeelding traceren is voltooid, maar het document ervan is gesloten -@msg Retype failed: internal error: its thread stopped (please report this bug) Opnieuw typen is mislukt: interne fout: de thread ervan is gestopt (meld deze bug alsjeblieft) -@msg Retype finished, but the document or its selection changed meanwhile: run it again Opnieuw typen is voltooid, maar het document of de selectie ervan is intussen gewijzigd: voer het opnieuw uit @msg Image Trace finished, but the image or its settings changed meanwhile: trace it again Afbeelding traceren is voltooid, maar de afbeelding of de instellingen ervan zijn intussen gewijzigd: traceer de afbeelding opnieuw @msg Image Trace finished, but its document was reverted: trace it again Afbeelding traceren is voltooid, maar het document ervan is teruggezet: traceer de afbeelding opnieuw @msg Import SVG Filter reads SVG files, not SVGZ SVG-filter importeren leest SVG-bestanden, geen SVGZ diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index 6c64921599..a15eda9804 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -423,7 +423,6 @@ Reset Retype Panel Resetuj panel Przepisz List Matching Fonts Wyświetl pasujące czcionki Retype Preview Podgląd w panelu Przepisz -@msg `installed` must be true, false or null `installed` musi mieć wartość true, false lub null @msg `count` must be a whole number from 1 to 96 `count` musi być liczbą całkowitą od 1 do 96 @msg `size` must be small, medium or large `size` musi mieć wartość small, medium lub large @msg `text` must be a string of at most 100 characters `text` musi być ciągiem o długości co najwyżej 100 znaków @@ -9126,8 +9125,6 @@ breakText Glyphs Glify @msg Image Trace failed: internal error: its thread stopped (please report this bug) Obrys obrazu nie powiódł się: błąd wewnętrzny: jego wątek został zatrzymany (zgłoś ten błąd) @msg Image Trace failed: {e} Obrys obrazu nie powiódł się: {e} @msg Image Trace finished, but its document was closed Obrys obrazu został ukończony, ale jego dokument został zamknięty -@msg Retype failed: internal error: its thread stopped (please report this bug) Przepisywanie nie powiodło się: błąd wewnętrzny: jego wątek został zatrzymany (zgłoś ten błąd) -@msg Retype finished, but the document or its selection changed meanwhile: run it again Przepisywanie zostało ukończone, ale dokument lub jego zaznaczenie zmieniły się w międzyczasie: uruchom je ponownie @msg Image Trace finished, but the image or its settings changed meanwhile: trace it again Obrys obrazu został ukończony, ale obraz lub jego ustawienia zmieniły się w międzyczasie: obrysuj go ponownie @msg Image Trace finished, but its document was reverted: trace it again Obrys obrazu został ukończony, ale jego dokument został przywrócony: obrysuj go ponownie @msg Join: a subpath went missing Połącz: brakuje ścieżki podrzędnej diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index ffabf1b70e..3d59e8a61b 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -1278,7 +1278,6 @@ antiAlias Sharp Nítido Reset Retype Panel Redefinir Painel Redigitar List Matching Fonts Listar Fontes Correspondentes Retype Preview Visualização do Painel Redigitar -@msg `installed` must be true, false or null `installed` deve ser true, false ou null @msg `count` must be a whole number from 1 to 96 `count` deve ser um número inteiro de 1 a 96 @msg `size` must be small, medium or large `size` deve ser small, medium ou large @msg `text` must be a string of at most 100 characters `text` deve ser uma string de no máximo 100 caracteres @@ -9032,8 +9031,6 @@ swatch Yellow Green Verde-amarelado @msg Image Trace failed: internal error: its thread stopped (please report this bug) O Rastreamento de Imagem falhou: erro interno: a thread dele parou (informe este erro) @msg Image Trace failed: {e} O Rastreamento de Imagem falhou: {e} @msg Image Trace finished, but its document was closed O Rastreamento de Imagem terminou, mas o documento dele foi fechado -@msg Retype failed: internal error: its thread stopped (please report this bug) O Redigitar falhou: erro interno: a thread dele parou (informe este erro) -@msg Retype finished, but the document or its selection changed meanwhile: run it again O Redigitar terminou, mas o documento ou a seleção dele mudou nesse meio-tempo: execute-o novamente @msg Image Trace finished, but the image or its settings changed meanwhile: trace it again O Rastreamento de Imagem terminou, mas a imagem ou as configurações dela mudaram nesse meio-tempo: rastreie-a novamente @msg Image Trace finished, but its document was reverted: trace it again O Rastreamento de Imagem terminou, mas o documento dele foi revertido: rastreie-a novamente @msg Import SVG Filter reads SVG files, not SVGZ Importar Filtro SVG lê arquivos SVG, não SVGZ diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index 24a1bb356a..65539e3647 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -1407,7 +1407,6 @@ font-technology Variable Вариативные Reset Retype Panel Сбросить панель «Перенабор» List Matching Fonts Список подходящих шрифтов Retype Preview Просмотр в панели «Перенабор» -@msg `installed` must be true, false or null `installed` должно быть true, false или null @msg `count` must be a whole number from 1 to 96 `count` должно быть целым числом от 1 до 96 @msg `size` must be small, medium or large `size` должно быть small, medium или large @msg `text` must be a string of at most 100 characters `text` должно быть строкой длиной не более 100 символов @@ -8967,8 +8966,6 @@ shape Open Открытый @msg Image Trace failed: internal error: its thread stopped (please report this bug) Трассировка изображения не выполнена: внутренняя ошибка: её поток остановился (сообщите об этой ошибке) @msg Image Trace failed: {e} Трассировка изображения не выполнена: {e} @msg Image Trace finished, but its document was closed Трассировка изображения завершена, но её документ был закрыт -@msg Retype failed: internal error: its thread stopped (please report this bug) Перенабор не выполнен: внутренняя ошибка: его поток остановился (сообщите об этой ошибке) -@msg Retype finished, but the document or its selection changed meanwhile: run it again Перенабор завершён, но документ или его выделение за это время изменились: выполните его снова @msg Image Trace finished, but the image or its settings changed meanwhile: trace it again Трассировка изображения завершена, но изображение или его настройки за это время изменились: выполните трассировку снова @msg Import SVG Filter reads SVG files, not SVGZ Импорт фильтра SVG читает файлы SVG, а не SVGZ @msg Invalid dimension offset Недопустимое смещение размера diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index 880e87f386..20c82885ef 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -1363,7 +1363,6 @@ font-technology Variable Variabla Reset Retype Panel Återställ panelen Skriv om List Matching Fonts Lista matchande typsnitt Retype Preview Förhandsgranskning i panelen Skriv om -@msg `installed` must be true, false or null `installed` måste vara true, false eller null @msg `count` must be a whole number from 1 to 96 `count` måste vara ett heltal från 1 till 96 @msg `size` must be small, medium or large `size` måste vara small, medium eller large @msg `text` must be a string of at most 100 characters `text` måste vara en sträng på högst 100 tecken @@ -9400,8 +9399,6 @@ digits Hindi Hindi @msg Image Trace failed: {e} Bildkalkering misslyckades: {e} @msg Image Trace failed: internal error: its thread stopped (please report this bug) Bildkalkering misslyckades: internt fel: dess tråd stoppades (rapportera gärna felet) @msg Image Trace finished, but its document was closed Bildkalkeringen är klar, men dess dokument har stängts -@msg Retype failed: internal error: its thread stopped (please report this bug) Skriv om misslyckades: internt fel: dess tråd stoppades (rapportera gärna felet) -@msg Retype finished, but the document or its selection changed meanwhile: run it again Skriv om är klar, men dokumentet eller dess markering ändrades under tiden: kör det igen @msg Image Trace finished, but the image or its settings changed meanwhile: trace it again Bildkalkeringen är klar, men bilden eller dess inställningar ändrades under tiden: vektorisera den igen @msg Image Trace finished, but its document was reverted: trace it again Bildkalkeringen är klar, men dess dokument har återgått till sparad version: vektorisera den igen @msg imageMap `{m}`: none, client or server imageMap `{m}`: none, client eller server diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index d9019146a2..94de30a7e3 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -1358,7 +1358,6 @@ font-technology Variable Değişken Reset Retype Panel Yeniden Yaz Panelini Sıfırla List Matching Fonts Eşleşen Yazı Tiplerini Listele Retype Preview Yeniden Yaz Paneli Önizlemesi -@msg `installed` must be true, false or null `installed` true, false veya null olmalıdır @msg `count` must be a whole number from 1 to 96 `count` 1 ile 96 arasında bir tam sayı olmalıdır @msg `size` must be small, medium or large `size` small, medium veya large olmalıdır @msg `text` must be a string of at most 100 characters `text` en fazla 100 karakterlik bir dize olmalıdır @@ -8114,8 +8113,6 @@ axis Y Axis Y ekseni @msg Image Trace failed: internal error: its thread stopped (please report this bug) Görüntü İzleme başarısız oldu: iç hata: iş parçacığı durdu (lütfen bu hatayı bildirin) @msg Image Trace failed: {e} Görüntü İzleme başarısız oldu: {e} @msg Image Trace finished, but its document was closed Görüntü İzleme tamamlandı, ancak belgesi kapatılmıştı -@msg Retype failed: internal error: its thread stopped (please report this bug) Yeniden Yaz başarısız oldu: iç hata: iş parçacığı durdu (lütfen bu hatayı bildirin) -@msg Retype finished, but the document or its selection changed meanwhile: run it again Yeniden Yaz tamamlandı, ancak bu sırada belge veya seçimi değişti: yeniden çalıştırın @msg Image Trace finished, but the image or its settings changed meanwhile: trace it again Görüntü İzleme tamamlandı, ancak bu sırada görüntü veya ayarları değişti: yeniden izleyin @msg Image Trace finished, but its document was reverted: trace it again Görüntü İzleme tamamlandı, ancak belgesi geri döndürüldü: yeniden izleyin @msg Invalid dimension offset Geçersiz boyut ofseti diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index 5fa2114fc3..1ef88a68e4 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -1416,7 +1416,6 @@ font-technology Variable Варіативні Reset Retype Panel Скинути панель «Повторний набір» List Matching Fonts Список відповідних шрифтів Retype Preview Перегляд у панелі «Повторний набір» -@msg `installed` must be true, false or null `installed` має бути true, false або null @msg `count` must be a whole number from 1 to 96 `count` має бути цілим числом від 1 до 96 @msg `size` must be small, medium or large `size` має бути small, medium або large @msg `text` must be a string of at most 100 characters `text` має бути рядком довжиною не більше 100 символів @@ -8620,8 +8619,6 @@ breakText Glyphs Гліфи @msg Image Trace failed: internal error: its thread stopped (please report this bug) Трасування зображення не вдалося: внутрішня помилка: його потік зупинився (будь ласка, повідомте про цю помилку) @msg Image Trace failed: {e} Трасування зображення не вдалося: {e} @msg Image Trace finished, but its document was closed Трасування зображення завершено, але його документ закрито -@msg Retype failed: internal error: its thread stopped (please report this bug) Повторний набір не вдався: внутрішня помилка: його потік зупинився (будь ласка, повідомте про цю помилку) -@msg Retype finished, but the document or its selection changed meanwhile: run it again Повторний набір завершено, але документ або його виділення тим часом змінилися: виконайте його ще раз @msg Image Trace finished, but the image or its settings changed meanwhile: trace it again Трасування зображення завершено, але зображення або його параметри тим часом змінилися: виконайте трасування ще раз @msg Image Trace finished, but its document was reverted: trace it again Трасування зображення завершено, але його документ було повернуто до збереженої версії: виконайте трасування ще раз @msg Import SVG Filter reads SVG files, not SVGZ Імпорт фільтра SVG читає файли SVG, а не SVGZ diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index 03031f125f..0aba1ddbb0 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -1656,7 +1656,6 @@ digits Malayalam Malayalam Reset Retype Panel Đặt lại bảng Gõ lại List Matching Fonts Liệt kê phông khớp Retype Preview Xem trước trong bảng Gõ lại -@msg `installed` must be true, false or null `installed` phải là true, false hoặc null @msg `count` must be a whole number from 1 to 96 `count` phải là số nguyên từ 1 đến 96 @msg `size` must be small, medium or large `size` phải là small, medium hoặc large @msg `text` must be a string of at most 100 characters `text` phải là chuỗi tối đa 100 ký tự @@ -6963,8 +6962,6 @@ axis Y Axis Trục Y The plug-in is computing… Plug-in đang tính toán… Inspect Plug-in Kiểm tra plug-in Cancel Plug-in Run Hủy lần chạy plug-in -@msg Retype failed: internal error: its thread stopped (please report this bug) Gõ lại thất bại: lỗi nội bộ: luồng của nó đã dừng (vui lòng báo cáo lỗi này) -@msg Retype finished, but the document or its selection changed meanwhile: run it again Gõ lại đã chạy xong, nhưng tài liệu hoặc vùng chọn của nó đã thay đổi trong lúc đó: hãy chạy lại @msg {_1} finished, but the document or the plug-in changed meanwhile: run it again {_1} đã chạy xong, nhưng tài liệu hoặc plug-in đã thay đổi trong lúc đó: hãy chạy lại @msg Running “{name}”… Đang chạy “{name}”… @msg a live effect runs while the document is drawn, so it can't be `heavy` hiệu ứng trực tiếp chạy trong lúc tài liệu được vẽ nên không thể là `heavy` diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index a6a7870ab3..abac760a5f 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -1352,7 +1352,6 @@ antiAlias Sharp 锐利 Reset Retype Panel 重置重新键入面板 List Matching Fonts 列出匹配字体 Retype Preview 重新键入面板预览 -@msg `installed` must be true, false or null `installed` 必须是 true、false 或 null @msg `count` must be a whole number from 1 to 96 `count` 必须是 1 到 96 之间的整数 @msg `size` must be small, medium or large `size` 必须是 small、medium 或 large @msg `text` must be a string of at most 100 characters `text` 必须是不超过 100 个字符的字符串 @@ -9135,8 +9134,6 @@ breakText Glyphs 字形 @msg Image Trace failed: internal error: its thread stopped (please report this bug) 图像描摹失败:内部错误:其线程已停止 (请报告此错误) @msg Image Trace failed: {e} 图像描摹失败:{e} @msg Image Trace finished, but its document was closed 图像描摹已完成,但其文档已关闭 -@msg Retype failed: internal error: its thread stopped (please report this bug) 重新键入失败:内部错误:其线程已停止 (请报告此错误) -@msg Retype finished, but the document or its selection changed meanwhile: run it again 重新键入已完成,但文档或其选区在此期间发生了更改:请重新运行 @msg Image Trace finished, but the image or its settings changed meanwhile: trace it again 图像描摹已完成,但图像或其设置在此期间发生了更改:请重新描摹 @msg Image Trace finished, but its document was reverted: trace it again 图像描摹已完成,但其文档已恢复:请重新描摹 @msg Invalid dimension offset 尺寸标注的偏移无效 diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index c8e7773a28..940cafa660 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -1387,7 +1387,6 @@ font-technology Variable 可變 Reset Retype Panel 重設重新鍵入面板 List Matching Fonts 列出相符字體 Retype Preview 重新鍵入面板預覽 -@msg `installed` must be true, false or null `installed` 必須是 true、false 或 null @msg `count` must be a whole number from 1 to 96 `count` 必須是介於 1 到 96 的整數 @msg `size` must be small, medium or large `size` 必須是 small、medium 或 large @msg `text` must be a string of at most 100 characters `text` 必須是不超過 100 個字元的字串 @@ -9071,8 +9070,6 @@ breakText Glyphs 字符 @msg Image Trace failed: internal error: its thread stopped (please report this bug) 影像描圖失敗:內部錯誤:其執行緒已停止 (請回報此錯誤) @msg Image Trace failed: {e} 影像描圖失敗:{e} @msg Image Trace finished, but its document was closed 影像描圖已完成,但其文件已關閉 -@msg Retype failed: internal error: its thread stopped (please report this bug) 重新鍵入失敗:內部錯誤:其執行緒已停止 (請回報此錯誤) -@msg Retype finished, but the document or its selection changed meanwhile: run it again 重新鍵入已完成,但文件或其選取範圍在此期間已變更:請重新執行 @msg Image Trace finished, but the image or its settings changed meanwhile: trace it again 影像描圖已完成,但影像或其設定在此期間已變更:請重新描圖 @msg Image Trace finished, but its document was reverted: trace it again 影像描圖已完成,但其文件已回復:請重新描圖 @msg Invalid dimension offset 尺寸標註位移無效 diff --git a/crates/ui-egui/src/tests/retype_runs.rs b/crates/ui-egui/src/tests/retype_runs.rs index f7b8f22084..fa06a5c99b 100644 --- a/crates/ui-egui/src/tests/retype_runs.rs +++ b/crates/ui-egui/src/tests/retype_runs.rs @@ -35,10 +35,9 @@ fn has_type(app: &VectorcraftApp) -> bool { found } -/// Draws the progress window at `time` seconds → the texts it drew. +/// Draws the progress window at `time` seconds in a frame as the hosts run it → the texts it drew. fn progress(app: &mut VectorcraftApp, ctx: &egui::Context, time: f64) -> String { - let mut out = ctx.run_ui(egui::RawInput { time: Some(time), ..Default::default() }, |ui| export_progress::show(app, ui)); - out.textures_delta.clear(); + let out = crate::testing::part_frame(app, ctx, egui::RawInput { time: Some(time), ..Default::default() }, export_progress::show); let mut texts = String::new(); for shape in out.shapes { if let egui::epaint::Shape::Text(t) = shape.shape { @@ -67,14 +66,12 @@ fn type_retype_searches_off_the_ui_thread_then_retypes_as_one_undo_step() { #[test] fn starting_a_search_asks_for_a_frame() { let (mut app, _) = outlined(); - let ctx = egui::Context::default(); - app.adopt_context(&ctx); + let ctx = crate::testing::ui_context(); for _ in 0..5 { + crate::testing::part_frame(&mut app, &ctx, Default::default(), |_, _| {}); if !ctx.has_requested_repaint() { break; } - let mut out = ctx.run_ui(Default::default(), |_| {}); - out.textures_delta.clear(); } assert!(!ctx.has_requested_repaint(), "the context settled"); crate::menus::invoke(&mut app, "type.retype", json!({})); From a42bdf83998e310708bd1a943fbd78215ed7cb4b Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 25 Nov 2026 18:49:09 -0800 Subject: [PATCH 093/151] Variables: the highlighted-row test drives the panel through the panel harness The test of a second click on the highlighted variable clicks the row through tests::panel_harness::Panel instead of the file's hand-written frame loop. --- crates/ui-egui/src/panels/variables.rs | 31 ++++++++++++-------------- 1 file changed, 14 insertions(+), 17 deletions(-) diff --git a/crates/ui-egui/src/panels/variables.rs b/crates/ui-egui/src/panels/variables.rs index 257d986eb2..901db60fc4 100644 --- a/crates/ui-egui/src/panels/variables.rs +++ b/crates/ui-egui/src/panels/variables.rs @@ -963,26 +963,23 @@ mod tests { /// click on it selects the bound object. #[test] fn a_click_on_the_highlighted_row_selects_its_bound_object_again() { - use egui::accesskit::Role; + use crate::tests::panel_harness::Panel; let mut app = app_with_data(); let bound = app.session.doc().unwrap().doc.variables.objects_of("Name")[0]; - let mut d = Driver::new(); - let row = |d: &mut Driver, app: &mut VectorcraftApp| { - let nodes = d.nodes(app); - nodes.iter().find(|(_, n)| n.role() != Role::ColumnHeader && n.label() == Some("Name")).expect("the Name row").1.clone() - }; - let selected = |app: &VectorcraftApp| app.session.doc().unwrap().selection.objects.clone(); app.session.execute("select.set", &json!({"ids": []})).unwrap(); - let cell = row(&mut d, &mut app); - d.click(&mut app, &cell); - assert_eq!(highlighted_row(app.session.doc().unwrap()).as_deref(), Some("Name")); - assert_eq!(selected(&app), vec![bound], "the first click selects the bound object"); - app.session.execute("select.set", &json!({"ids": []})).unwrap(); - assert!(selected(&app).is_empty()); - let cell = row(&mut d, &mut app); - d.click(&mut app, &cell); - assert_eq!(highlighted_row(app.session.doc().unwrap()).as_deref(), Some("Name")); - assert_eq!(selected(&app), vec![bound], "a click on the highlighted row selects the bound object again"); + let mut p = Panel::new(app, show); + let selected = |p: &Panel| p.app().session.doc().unwrap().selection.objects.clone(); + let highlighted = |p: &Panel| highlighted_row(p.app().session.doc().unwrap()); + p.click("Name"); + assert_eq!(highlighted(&p).as_deref(), Some("Name")); + assert_eq!(selected(&p), vec![bound], "the first click selects the bound object"); + p.app().session.execute("select.set", &json!({"ids": []})).unwrap(); + assert!(selected(&p).is_empty()); + // A second later, so the two clicks are not a double click. + p.advance(1.0); + p.click("Name"); + assert_eq!(highlighted(&p).as_deref(), Some("Name")); + assert_eq!(selected(&p), vec![bound], "a click on the highlighted row selects the bound object again"); } /// The rows as the panel built them on every frame before [`cached_rows`] kept them: the From 0e2860ea8bdf603a3901d509acf51769ece422d8 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 25 Nov 2026 18:49:00 -0800 Subject: [PATCH 094/151] Preferences: Script File Access lists its rows in a craft scroll stack The list is a Stack with a vertical scroll, and each line is a Lazy child, so only the lines in view run. The row whose Revoke was clicked is returned from the list's body and revoked after the list is shown. --- .../ui-egui/src/prefs_dialog/script_access.rs | 42 ++++++++++--------- crates/ui-egui/src/prefs_dialog/tests.rs | 21 ++++++++++ 2 files changed, 43 insertions(+), 20 deletions(-) diff --git a/crates/ui-egui/src/prefs_dialog/script_access.rs b/crates/ui-egui/src/prefs_dialog/script_access.rs index bdf4b128f5..b0de2cd30d 100644 --- a/crates/ui-egui/src/prefs_dialog/script_access.rs +++ b/crates/ui-egui/src/prefs_dialog/script_access.rs @@ -7,9 +7,9 @@ use std::collections::BTreeMap; use craft::theme::TypeRole; use craft::theme::variant::Tone; use craft::ui::buttons::Button; -use craft::ui::contract::{Props as _, Show as _, ShowContainer as _, Sizing}; +use craft::ui::contract::{Lazy, Props as _, Scroll, Show as _, ShowContainer as _, Sizing}; use craft::ui::display::{Elide, Shade, Text}; -use craft::ui::layout_components::Row as Line; +use craft::ui::layout_components::{Row as Line, Stack}; use craft::ui::runtime::focus::FocusRequest; use serde_json::{Map, Value, json}; use vectorcraft_plugins::permissions; @@ -30,10 +30,10 @@ pub(super) const ERROR: &str = "__scriptAccessError"; /// The most characters of a path a row shows. const MAX_SHOWN_PATH: usize = 1024; -/// A line's height in the list. -const LINE_HEIGHT: f32 = 30.0; +/// How tall a line of the list is taken to be before it was first shown. +const LINE_ESTIMATE: f32 = 30.0; -/// The list's height before it scrolls. +/// The height the list offers its lines before it scrolls. const LIST_HEIGHT: f32 = 180.0; /// One script and path with kept access. @@ -193,26 +193,24 @@ pub(super) fn show(app: &mut VectorcraftApp, access: &mut Option, ui: &m lines.push(Entry::Grant(i)); } let focus = state.focus.take(); - let mut revoke_at = None; - // The list is as tall as its lines, up to LIST_HEIGHT, and draws only the lines in view. - let spacing = ui.spacing().item_spacing.y; - let height = ((LINE_HEIGHT + spacing) * lines.len() as f32 - spacing).min(LIST_HEIGHT); - let scroll = egui::ScrollArea::vertical().id_salt("prefs-script-access").max_height(LIST_HEIGHT).min_scrolled_height(height); - scroll.auto_shrink([false, true]).show_rows(ui, LINE_HEIGHT, lines.len(), |ui, range| { - for line in &lines[range] { - let size = egui::vec2(ui.available_width(), LINE_HEIGHT); + // The body returns the row whose Revoke was clicked; the revoke runs after the list is shown. + let list = Stack::new().id_salt("prefs-script-access").label(tl!("Script File Access")).fill_width(); + let shown_list = list.scroll(Scroll::vertical()).room_height(LIST_HEIGHT).show(ui, |ui, _| { + let mut clicked = None; + // Each line runs only while it is in view, so a long list costs no more per frame than a short one. + for line in &lines { match *line { Entry::Script(i) => { let script = &rows[i].shown_script; - ui.allocate_ui(size, |ui| { + Lazy::new(("prefs-script", i), LINE_ESTIMATE).show(ui, |ui| { Text::new(shown(script)).role(TypeRole::BodyStrong).elide(Elide::Path).tooltip(shown_whole(script)).show(ui); }); } Entry::Grant(i) => { let row = &rows[i]; - let (script, path) = (shown_whole(&row.shown_script), shown_whole(&row.shown_path)); - ui.allocate_ui(size, |ui| { - Line::new().show(ui, |ui, _| { + let shown_line = Lazy::new(("prefs-script-row", i), LINE_ESTIMATE).reveal(focus == Some(i)).show(ui, |ui| { + let (script, path) = (shown_whole(&row.shown_script), shown_whole(&row.shown_path)); + let line = Line::new().id_salt(("prefs-script-row", i)).show(ui, |ui, _| { Text::new(shown(&row.shown_path)).elide(Elide::Path).sizing(Sizing::FillWidth).tooltip(path.clone()).show(ui); Text::new(access_label(row.access)).shade(Shade::Muted).show(ui); // A screen reader names the script and the path along with the button. @@ -221,15 +219,19 @@ pub(super) fn show(app: &mut VectorcraftApp, access: &mut Option, ui: &m if focus == Some(i) { button = button.request_focus(FocusRequest::Take); } - if button.show(ui).clicked() { - revoke_at = Some(i); - } + button.show(ui).clicked() }); + line.inner }); + if shown_line.flatten() == Some(true) { + clicked = Some(i); + } } } } + clicked }); + let revoke_at = shown_list.inner.flatten(); Text::new(tl!("Revoke removes the access kept for every version of the script. A folder's access covers everything in it.")) .shade(Shade::Muted) .show(ui); diff --git a/crates/ui-egui/src/prefs_dialog/tests.rs b/crates/ui-egui/src/prefs_dialog/tests.rs index c148173378..37772ba113 100644 --- a/crates/ui-egui/src/prefs_dialog/tests.rs +++ b/crates/ui-egui/src/prefs_dialog/tests.rs @@ -807,6 +807,27 @@ fn script_file_access_lists_each_script_and_path_once_and_revoke_removes_them() let _ = std::fs::remove_dir_all(store.parent().unwrap()); } +/// A long list scrolls and draws only the lines in view: of 200 rows, the first shows and the last +/// does not, and fewer than 200 Revoke buttons are drawn. +#[test] +fn script_file_access_draws_only_the_rows_in_view() { + let dir = std::env::temp_dir().join("vc-ui-prefs-grants-nowhere"); + let script = dir.join("a.jsx"); + let paths: Vec<_> = (0..200).map(|n| dir.join(format!("out{n:03}.txt"))).collect(); + let grants: Vec = paths.iter().map(|p| grant(&script, p, "1", false, false)).collect(); + let (mut a, store) = app_with_grants("grants-many", Value::Array(grants)); + open(&mut a, Some("General")); + assert_eq!(access_rows(&a).len(), 200); + let texts = access_texts(&mut a); + let painted = |label: &str| texts.iter().filter(|(t, _)| t == label).count(); + let (first, last) = (paths[0].to_string_lossy(), paths[199].to_string_lossy()); + assert_eq!(painted(&first), 1, "the first row shows: {texts:?}"); + assert_eq!(painted(&last), 0, "the last row is out of view: {texts:?}"); + let revokes = painted("Revoke"); + assert!(revokes > 0 && revokes < 200, "{revokes} Revoke buttons drawn"); + let _ = std::fs::remove_dir_all(store.parent().unwrap()); +} + /// Revoke on a row whose grants were removed elsewhere removes nothing and says so; with no kept /// grants the section says there are none, and a session without a settings folder (the web among /// them) shows no section. From 9c93b32c123e269293bff42196d882d222053f57 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 25 Nov 2026 19:41:01 -0800 Subject: [PATCH 095/151] Color Wheel: an opacity edit keeps the HSL and OKLCH picked last The opacity row re-keyed only the remembered HSB after its edit, so a hue given to a gray in the HSL or OKLCH rows jumped back to the gray's own hue when Opacity changed. One helper now moves all three records to the edited paint. --- crates/ui-egui/src/panels/color_wheel.rs | 23 +++++++++++++------ .../src/panels/tests_color_wheel_opacity.rs | 17 ++++++++++++++ 2 files changed, 33 insertions(+), 7 deletions(-) diff --git a/crates/ui-egui/src/panels/color_wheel.rs b/crates/ui-egui/src/panels/color_wheel.rs index 96354161a1..1fe1cf2d0c 100644 --- a/crates/ui-egui/src/panels/color_wheel.rs +++ b/crates/ui-egui/src/panels/color_wheel.rs @@ -1050,6 +1050,15 @@ fn recall( kept } +/// Move the record in `slot` from owner `was` to owner `now`, when `was` holds it. +fn rekey(slot: &mut Option<(Owner, [f32; 3], T)>, was: &Owner, now: &Owner) { + if let Some((owner, ..)) = slot + && owner == was + { + *owner = now.clone(); + } +} + /// The HSB a color shows on the wheel: that of its display sRGB through `cms`. pub(crate) fn display_hsb(cms: &Cms, c: &Color) -> [f32; 3] { rgb_to_hsb(cms.display_rgb(c)) @@ -1510,13 +1519,13 @@ fn show_rows(app: &mut VectorcraftApp, panel: &mut WheelUi, ui: &mut Ui, cx: &Pi let shown = color.unwrap_or(app.session.last_solid); let owner = color.map(|c| Owner::of(app, tgt, c)); opacity_row(app, panel, ui, tgt, &shown, cx.cms); - // An opacity edit of a gradient stop or point changes the gradient its owner holds, and the - // HSB picked last stays with the new gradient. - if let (Some(c), Some(was)) = (color, owner) - && let Some((remembered, ..)) = &mut panel.hsb - && *remembered == was - { - *remembered = Owner::of(app, tgt, c); + // An opacity edit adds an undo step, and on a gradient stop or point it also changes the + // gradient its owner holds. The HSB, HSL and OKLCH picked last stay with the edited paint. + if let (Some(c), Some(was)) = (color, owner) { + let now = Owner::of(app, tgt, c); + rekey(&mut panel.hsb, &was, &now); + rekey(&mut panel.hsl, &was, &now); + rekey(&mut panel.oklch, &was, &now); } } else { end_opacity_drag(app, panel); diff --git a/crates/ui-egui/src/panels/tests_color_wheel_opacity.rs b/crates/ui-egui/src/panels/tests_color_wheel_opacity.rs index 27def08cd7..ea7aec7096 100644 --- a/crates/ui-egui/src/panels/tests_color_wheel_opacity.rs +++ b/crates/ui-egui/src/panels/tests_color_wheel_opacity.rs @@ -165,6 +165,23 @@ fn screen_readers_read_and_set_the_opacity() { assert!((fill_opacity(&p.app()) - 0.24).abs() < 1e-6); } +/// A hue given to a gray in the HSL or OKLCH rows stays after the row's opacity edit, as the wheel's +/// HSB hue does. +#[test] +fn an_opacity_edit_keeps_the_hue_given_to_a_gray() { + for (rows, hue) in [("hsl", "HSL Hue"), ("oklch", "Hue")] { + let mut a = app(); + a.run("paint.setFill", json!({"color": "#808080"})).unwrap(); + a.run("ui.colorWheel", json!({"sliders": rows})).unwrap(); + let mut p = Panel::new(a); + p.set(hue, 240.0); + assert_eq!(p.number(hue), Some(240.0), "{rows}: the gray takes the hue"); + act(&mut p, AccessActionKind::SetValue(40.0)); + assert!((fill_opacity(&p.app()) - 0.4).abs() < 1e-6, "{rows}: the opacity is set"); + assert_eq!(p.number(hue), Some(240.0), "{rows}: the hue is kept"); + } +} + /// The stroke proxy in front: the row sets the stroke item's opacity and leaves the fill's. #[test] fn with_the_stroke_in_front_the_row_sets_the_stroke() { From 22000f9eaaab52610554955bdbbb6a21463ae6cb Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 25 Nov 2026 19:52:01 -0800 Subject: [PATCH 096/151] Tests: the Retype progress window is read in the host's frame In a frame as the hosts run it, the window draws in its first frame, so the test reads it there; after Cancel, the next two frames do not show it. --- crates/ui-egui/src/tests/retype_runs.rs | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/crates/ui-egui/src/tests/retype_runs.rs b/crates/ui-egui/src/tests/retype_runs.rs index fa06a5c99b..946c94b865 100644 --- a/crates/ui-egui/src/tests/retype_runs.rs +++ b/crates/ui-egui/src/tests/retype_runs.rs @@ -107,12 +107,14 @@ fn the_progress_window_shows_a_search() { if let Some(r) = app.retype_runs.running.as_mut() { r.started -= DELAY; } - progress(&mut app, &ctx, DELAY + 0.05); // a new window measures itself unseen first - let shown = progress(&mut app, &ctx, DELAY + 0.1); + let shown = progress(&mut app, &ctx, DELAY + 0.05); assert!(shown.contains("Finding matching fonts…") && shown.contains("Reading the installed fonts…"), "{shown}"); assert!(shown.contains("Cancel") && !shown.contains("Continue in Background"), "{shown}"); assert_eq!(app.run("retype.cancelSearch", json!({})).unwrap(), json!({"cancelled": 1})); - assert!(!progress(&mut app, &ctx, DELAY + 1.0).contains("Finding matching fonts"), "a canceled search isn't shown"); + // The window open in the last frame is gone from the next two. + for time in [DELAY + 1.0, DELAY + 1.1] { + assert!(!progress(&mut app, &ctx, time).contains("Finding matching fonts"), "a canceled search isn't shown"); + } retype_runs::wait(&mut app); assert_eq!(undos(&app), before, "canceled: nothing changes"); } From 8c39b153a96bc563791208ad29f6531109508271 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 25 Nov 2026 20:04:33 -0800 Subject: [PATCH 097/151] Canvas: a tool drag's release modifiers come from the craft pointer frame The release modifiers are read from the pointer frame's pick_mods, the modifiers of the pass's button release with the latched ones added, in place of raw egui pointer events. The release-modifier tests drive the whole app through testing::app_frame. --- crates/ui-egui/src/canvas/tests.rs | 44 +++++++++++++---------- crates/ui-egui/src/canvas/tool_adapter.rs | 29 ++++++--------- 2 files changed, 36 insertions(+), 37 deletions(-) diff --git a/crates/ui-egui/src/canvas/tests.rs b/crates/ui-egui/src/canvas/tests.rs index 8b6ac373af..0a0ad98faa 100644 --- a/crates/ui-egui/src/canvas/tests.rs +++ b/crates/ui-egui/src/canvas/tests.rs @@ -533,8 +533,14 @@ fn cmd_with_another_tool_drags_with_the_selection_tool_used_last() { assert_eq!(cmd_drag(&mut app, inside, inside), "selection"); } -/// A Rectangle tool on a new 400 × 300 document, after one frame, with Smart Guides and Snap to -/// Point off → (the app, its context, the canvas view). +/// One frame of the whole app on `ctx` with `events`, in a 1600 × 850 window, as the hosts run it. +fn app_step(app: &mut VectorcraftApp, ctx: &egui::Context, events: Vec) { + let screen = egui::Rect::from_min_size(Pos2::ZERO, vec2(1600.0, 850.0)); + crate::testing::app_frame(app, ctx, egui::RawInput { screen_rect: Some(screen), events, ..Default::default() }); +} + +/// A Rectangle tool on a new 400 × 300 document in the whole app, after three frames, with Smart +/// Guides and Snap to Point off → (the app, its context, the canvas view). fn rectangle_tool() -> (VectorcraftApp, egui::Context, craft::behavior::CanvasView) { let mut app = VectorcraftApp::new(Session::new(), Default::default()); app.session.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); @@ -542,7 +548,9 @@ fn rectangle_tool() -> (VectorcraftApp, egui::Context, craft::behavior::CanvasVi app.ui.view.snap_to_point = false; app.select_tool("rectangle"); let ctx = crate::testing::ui_context(); - frame(&mut app, &ctx, vec![]); + for _ in 0..3 { + app_step(&mut app, &ctx, vec![]); + } let xf = app.canvas_view().unwrap(); (app, ctx, xf) } @@ -578,15 +586,15 @@ fn tool_drag_ends_with_the_modifiers_of_its_button_release() { let (mut app, ctx, xf) = rectangle_tool(); let (from, to) = (xf.to_screen(Point::new(100.0, 100.0)), xf.to_screen(Point::new(160.0, 130.0))); let none = egui::Modifiers::NONE; - frame(&mut app, &ctx, vec![egui::Event::PointerMoved(from)]); - frame(&mut app, &ctx, vec![primary(from, true, none)]); - frame(&mut app, &ctx, vec![egui::Event::PointerMoved(from.lerp(to, 0.5))]); - frame( + app_step(&mut app, &ctx, vec![egui::Event::PointerMoved(from)]); + app_step(&mut app, &ctx, vec![primary(from, true, none)]); + app_step(&mut app, &ctx, vec![egui::Event::PointerMoved(from.lerp(to, 0.5))]); + app_step( &mut app, &ctx, vec![egui::Event::PointerMoved(to), egui::Event::ModifiersChanged(held), primary(to, false, held), egui::Event::ModifiersChanged(after)], ); - frame(&mut app, &ctx, vec![egui::Event::ModifiersChanged(none)]); + app_step(&mut app, &ctx, vec![egui::Event::ModifiersChanged(none)]); let paths = drawn_paths(&app); assert_eq!(paths.len(), 1, "the drag draws one rectangle"); paths[0] @@ -606,11 +614,11 @@ fn tool_drag_ends_with_the_modifiers_of_its_button_release() { fn shift_pressed_at_a_still_release_constrains_the_tool_drag() { let (mut app, ctx, xf) = rectangle_tool(); let (from, to) = (xf.to_screen(Point::new(100.0, 100.0)), xf.to_screen(Point::new(160.0, 130.0))); - frame(&mut app, &ctx, vec![egui::Event::PointerMoved(from), primary(from, true, egui::Modifiers::NONE)]); - frame(&mut app, &ctx, vec![egui::Event::PointerMoved(from.lerp(to, 0.5))]); - frame(&mut app, &ctx, vec![egui::Event::PointerMoved(to)]); - frame(&mut app, &ctx, vec![egui::Event::ModifiersChanged(egui::Modifiers::SHIFT), primary(to, false, egui::Modifiers::SHIFT)]); - frame(&mut app, &ctx, vec![egui::Event::ModifiersChanged(egui::Modifiers::NONE)]); + app_step(&mut app, &ctx, vec![egui::Event::PointerMoved(from), primary(from, true, egui::Modifiers::NONE)]); + app_step(&mut app, &ctx, vec![egui::Event::PointerMoved(from.lerp(to, 0.5))]); + app_step(&mut app, &ctx, vec![egui::Event::PointerMoved(to)]); + app_step(&mut app, &ctx, vec![egui::Event::ModifiersChanged(egui::Modifiers::SHIFT), primary(to, false, egui::Modifiers::SHIFT)]); + app_step(&mut app, &ctx, vec![egui::Event::ModifiersChanged(egui::Modifiers::NONE)]); let paths = drawn_paths(&app); assert_eq!(paths.len(), 1, "the drag draws one rectangle"); assert!((paths[0].width() - paths[0].height()).abs() < 1e-3, "Shift pressed at a still release draws a square: {:?}", paths[0]); @@ -625,13 +633,13 @@ fn the_move_of_a_releasing_frame_counts_for_the_tool_drag() { let (mut app, ctx, xf) = rectangle_tool(); let (from, to) = (xf.to_screen(Point::new(100.0, 100.0)), xf.to_screen(Point::new(160.0, 130.0))); let none = egui::Modifiers::NONE; - frame(&mut app, &ctx, vec![egui::Event::PointerMoved(from), primary(from, true, none)]); - frame(&mut app, &ctx, vec![egui::Event::PointerMoved(from.lerp(to, 0.5))]); + app_step(&mut app, &ctx, vec![egui::Event::PointerMoved(from), primary(from, true, none)]); + app_step(&mut app, &ctx, vec![egui::Event::PointerMoved(from.lerp(to, 0.5))]); if space { - frame(&mut app, &ctx, vec![space_key(true)]); + app_step(&mut app, &ctx, vec![space_key(true)]); } - frame(&mut app, &ctx, vec![egui::Event::PointerMoved(to), primary(to, false, none)]); - frame(&mut app, &ctx, if space { vec![space_key(false)] } else { vec![] }); + app_step(&mut app, &ctx, vec![egui::Event::PointerMoved(to), primary(to, false, none)]); + app_step(&mut app, &ctx, if space { vec![space_key(false)] } else { vec![] }); let paths = drawn_paths(&app); assert_eq!(paths.len(), 1, "the drag draws one rectangle"); paths[0] diff --git a/crates/ui-egui/src/canvas/tool_adapter.rs b/crates/ui-egui/src/canvas/tool_adapter.rs index 8f177c1968..b857973dfd 100644 --- a/crates/ui-egui/src/canvas/tool_adapter.rs +++ b/crates/ui-egui/src/canvas/tool_adapter.rs @@ -133,17 +133,6 @@ pub(crate) fn tool_enter(app: &mut VectorcraftApp, mods: Mods, view: ViewInfo) - opened } -/// The modifiers held when the primary button went up in this pass: its first release, as a pass carries a press only -/// as its last pointer event. `None` without a release in the pass. -fn release_mods(ctx: &egui::Context) -> Option { - ctx.input(|i| { - i.events.iter().find_map(|e| match e { - egui::Event::PointerButton { button: egui::PointerButton::Primary, pressed: false, modifiers, .. } => Some(*modifiers), - _ => None, - }) - }) -} - /// The session as a tool for one pass. The host's trait takes `&self` for the cursor and the claims, which the /// session answers through `&mut`, so the app sits in a cell. struct SessionTool<'a> { @@ -161,12 +150,14 @@ impl<'a> SessionTool<'a> { Self { app: RefCell::new(app), view, carrying: Cell::new(false), ctx: ui.ctx().clone(), layer: ui.layer_id() } } - /// `ev` with Shift, Alt, Cmd and Ctrl as they were held when the primary button went up in this pass to end the - /// gesture, instead of as they are at the end of the pass: a modifier pressed or let go after the release does not - /// count for it. Space and Backtick stay as the host holds them. Unchanged without a release in the pass. - fn at_release(&self, mut ev: PointerEvent) -> PointerEvent { - if let Some(m) = release_mods(&self.ctx) { - ev.mods = tool_mods(craft::keymap::Mods::from_egui(&m, crate::keymap::platform()), ev.mods.space); + /// `ev` with Shift, Alt, Cmd and Ctrl as they were held when the gesture's button went up in this pass, latched ones + /// included (the pointer frame's `pick_mods`), instead of as they are at the end of the pass: a modifier pressed or + /// let go after the release does not count for it. Space and Backtick stay as the host holds them. Unchanged in a + /// pass where that button did not come up. + fn at_release(&self, pointer: &ToolPointer, mut ev: PointerEvent) -> PointerEvent { + let frame = craft::ui::runtime::pointer::frame(&self.ctx); + if frame.release == Some(pointer.button) { + ev.mods = tool_mods(frame.pick_mods, ev.mods.space); } ev } @@ -344,7 +335,7 @@ impl CanvasTool for SessionTool<'_> { let carried = super::drops::carry_out(&mut self.app(), cx, pointer, covered); if !carried { // The moves of the pass that releases the press came before its release, with the keys held then. - let ev = self.at_release(pointer_event(PointerKind::Drag, pointer, cx)); + let ev = self.at_release(pointer, pointer_event(PointerKind::Drag, pointer, cx)); dispatch(&mut self.app(), &ev, self.view); self.app().canvas.last_drag = Some((pointer.pos, ev)); } @@ -363,7 +354,7 @@ impl CanvasTool for SessionTool<'_> { } drop(app); // The press ends where it went up, with the keys held at its release. - let up = self.at_release(pointer_event(PointerKind::Up, pointer, cx)); + let up = self.at_release(pointer, pointer_event(PointerKind::Up, pointer, cx)); let covered = self.covered(pointer); let carried = super::drops::carried(&self.app(), cx, pointer, covered); self.app().canvas.panes.released_from = carried.as_ref().map(|art| (art.document, art.revision)); From 844980f135d7fdafa59b163820e563db41d8b399 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 25 Nov 2026 23:58:46 -0800 Subject: [PATCH 098/151] Scripts: read the chosen script once when startup scripts are skipped The chosen script is prepared only after the skip check, so a skipped round leaves its read to script.run. The new startup tests use a TempDir that removes the folder when the test ends. --- crates/engine/src/cmd/scripts.rs | 4 +++- crates/ui-egui/src/tests/scripts_menu.rs | 19 +++---------------- 2 files changed, 6 insertions(+), 17 deletions(-) diff --git a/crates/engine/src/cmd/scripts.rs b/crates/engine/src/cmd/scripts.rs index a683a0f51d..2bade13aa5 100644 --- a/crates/engine/src/cmd/scripts.rs +++ b/crates/engine/src/cmd/scripts.rs @@ -550,7 +550,6 @@ fn startup_run(s: &mut Session, p: &Value) -> Result { // parameters are checked as `script.run` checks them. if let Some(then) = &then { super::params::check_params("script.run", then)?; - prepare(s, then)?; } let root = match (s.startup_skip(), s.startup_scripts_dir()) { (None, Some(root)) => root.to_path_buf(), @@ -562,6 +561,9 @@ fn startup_run(s: &mut Session, p: &Value) -> Result { return Ok(out); } }; + if let Some(then) = &then { + prepare(s, then)?; + } let folder = root.to_string_lossy().into_owned(); // The folder is the app's: a refusal names it as the request may see it. crate::file_access::check_read(&folder).map_err(|e| super::fileio::naming_in_error(EngineError::Other(e), &folder))?; diff --git a/crates/ui-egui/src/tests/scripts_menu.rs b/crates/ui-egui/src/tests/scripts_menu.rs index e0604081fd..0683a1fe6b 100644 --- a/crates/ui-egui/src/tests/scripts_menu.rs +++ b/crates/ui-egui/src/tests/scripts_menu.rs @@ -25,10 +25,9 @@ fn ctx() -> egui::Context { CTX.with(Clone::clone) } -/// A fresh folder for test `name`, holding an empty `Scripts` folder. -fn folder(name: &str) -> std::path::PathBuf { - let dir = std::env::temp_dir().join(format!("vc-scripts-menu-{name}-{}", std::process::id())); - let _ = std::fs::remove_dir_all(&dir); +/// A fresh folder for test `name`, holding an empty `Scripts` folder, removed when the test ends. +fn folder(name: &str) -> vectorcraft_testkit::TempDir { + let dir = vectorcraft_testkit::TempDir::new(&format!("scripts-menu-{name}")); std::fs::create_dir_all(dir.join("Scripts")).unwrap(); dir } @@ -503,7 +502,6 @@ fn with_run_startup_scripts_on_a_listed_script_runs_after_the_startup_scripts() assert!(!app.session.script_running()); assert_eq!(started(&app).len(), 3); scripts_menu::finish(); - let _ = std::fs::remove_dir_all(dir); } #[test] @@ -522,7 +520,6 @@ fn with_run_startup_scripts_on_other_script_and_the_launch_run_the_startup_scrip finish(&mut app); assert_eq!(started(&app), ["a.jsx", "a.jsx", "chosen"]); assert_eq!(objects(&app), 4); - let _ = std::fs::remove_dir_all(dir); } #[test] @@ -555,7 +552,6 @@ fn with_run_startup_scripts_on_a_chosen_script_still_replies_as_script_run() { finish(&mut app); assert_eq!((&r["running"], &r["queued"], &r["startup"]["queued"]), (&json!(true), &json!(true), &json!(2)), "{r}"); assert_eq!(started(&app).last().map(String::as_str), Some("chosen")); - let _ = std::fs::remove_dir_all(dir); } #[test] @@ -585,7 +581,6 @@ fn a_stopped_startup_script_says_it_was_stopped_and_the_chosen_script_still_runs // The stopped startup script stays in sight when the chosen script ends, with its message in the hover. assert_eq!(app.ui.status, stopped); assert_eq!(app.ui.status_notes, Some((stopped.clone(), vec![stopped, "Ran chosen".to_string()]))); - let _ = std::fs::remove_dir_all(dir); } #[test] @@ -601,7 +596,6 @@ fn a_last_startup_script_that_cannot_start_shows_in_the_status_bar_when_the_runs finish(&mut app); assert_eq!(started(&app), ["a.jsx", "b.jsx"]); assert_eq!(app.ui.status, format!("b.jsx: {}", vectorcraft_engine::cmd::scripts::TOO_LARGE)); - let _ = std::fs::remove_dir_all(dir); } /// `dir`'s `Startup Scripts` folder, attached to `app`, holding only `0.jsx`, too large to run. @@ -628,7 +622,6 @@ fn a_launch_whose_only_startup_script_cannot_start_shows_it_in_the_status_bar() script_runs::poll(&mut app); assert_eq!(app.ui.status, shown); assert_eq!(objects(&app), 0); - let _ = std::fs::remove_dir_all(dir); } #[test] @@ -648,7 +641,6 @@ fn a_menu_run_after_a_first_startup_script_that_cannot_start_shows_it_and_runs_t // The failure stays in sight when the chosen script ends, with its message in the hover. assert_eq!(app.ui.status, shown); assert_eq!(app.ui.status_notes, Some((shown.clone(), vec![shown, "Ran chosen".to_string()]))); - let _ = std::fs::remove_dir_all(dir); } #[test] @@ -673,7 +665,6 @@ fn with_run_startup_scripts_on_other_script_with_a_missing_file_fails_before_the assert_eq!(app.ui.status, alone, "the error script.run gives, after the warning"); assert!(!app.session.script_running()); assert!(started(&app).is_empty(), "no startup script ran after the warning"); - let _ = std::fs::remove_dir_all(dir); } #[test] @@ -692,7 +683,6 @@ fn a_startup_scripts_folder_that_cannot_be_read_shows_in_the_status_bar_at_launc assert!(!app.session.script_running()); // The message names the folder without its path, which automation replies would show. assert_eq!(app.ui.status, "The Startup Scripts folder cannot be read"); - let _ = std::fs::remove_dir_all(dir); } #[test] @@ -712,7 +702,6 @@ fn a_menu_run_with_a_startup_scripts_folder_that_cannot_be_read_says_so_and_runs assert_eq!(started(&app), ["chosen"]); assert_eq!(app.ui.status, note, "the note stays in sight when the chosen script ends"); assert_eq!(app.ui.status_notes, Some((note.clone(), vec![note, "Ran chosen".to_string()]))); - let _ = std::fs::remove_dir_all(dir); } /// `dir`'s `Startup Scripts` folder, attached to `app`, holding one more entry than a listing reads @@ -745,7 +734,6 @@ fn a_startup_scripts_folder_not_read_in_full_shows_in_the_status_bar_at_launch_a assert_eq!(started(&app), ["chosen"]); assert_eq!(app.ui.status, note, "the note stays in sight when the chosen script ends"); assert_eq!(app.ui.status_notes, Some((note.to_string(), vec![note.to_string(), "Ran chosen".to_string()]))); - let _ = std::fs::remove_dir_all(dir); } #[test] @@ -765,5 +753,4 @@ fn startup_scripts_that_cannot_start_and_a_folder_not_read_in_full_all_stay_in_t // A reply with nothing left out keeps the message. script_runs::reply_notes(&mut app, &json!({"failed": [], "truncated": false, "unreadable": false})); assert_eq!(app.ui.status, "0.jsx: too large"); - let _ = std::fs::remove_dir_all(dir); } From d9b119a371d1a756265c084f633d2d909842409a Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 26 Nov 2026 00:18:32 -0800 Subject: [PATCH 099/151] Color Wheel: a channel just below sRGB counts as outside it The gamut test allowed 1e-4 beyond 0..1, so OKLCH colors such as L 0.01, C 0.01, H 0 were clipped at their own chroma and not reported as lowered, and the C track marked the wrong maximum. The allowance is now 1e-5, above the 1.7e-6 matrix round-trip error of sRGB boundary colors. --- crates/color/src/oklab.rs | 20 +++++++++++++++----- 1 file changed, 15 insertions(+), 5 deletions(-) diff --git a/crates/color/src/oklab.rs b/crates/color/src/oklab.rs index 7deb757f58..1279de689a 100644 --- a/crates/color/src/oklab.rs +++ b/crates/color/src/oklab.rs @@ -12,7 +12,7 @@ pub const CHROMA_FULL: f64 = 0.4; pub const POWERLESS_CHROMA: f64 = 0.000_004; /// How far outside 0..=1 an sRGB component may be and still count as inside the gamut. -const GAMUT_SLACK: f64 = 1e-4; +const GAMUT_SLACK: f64 = 1e-5; /// OKLCH `[l, c, h°]` of sRGB `rgb` (gamma encoded). Values outside 0..=1 are converted as they /// are. The hue is in 0..360, and 0 while the chroma is powerless. @@ -46,7 +46,7 @@ pub fn max_chroma(l: f64, h: f64) -> f64 { /// /// The chromas sRGB holds along the ray can come in several stretches: at the lightness and hue of /// blue the ray leaves sRGB at a chroma of about 0.266 and comes back at blue itself, about 0.313, -/// and near black the gamut slack opens stretches of its own. Each linear sRGB channel is a cubic +/// and the ray can leave and return near black as well. Each linear sRGB channel is a cubic /// in the chroma, so every stretch ends where a channel's cubic meets a bound of the gamut. The /// search finds each such chroma between the cubic's turning points and takes the largest one that /// fits. @@ -245,12 +245,10 @@ mod tests { } /// The largest chroma fits and is at least the largest one a scan in steps of 0.0005 finds, at - /// every hue and at lightnesses near black too, where the ray can come back into sRGB away from - /// any primary color's hue (L 0.02 and H 242° fit up to about 0.022 after leaving near 0.012). + /// every hue and at lightnesses near black too. #[test] fn the_largest_chroma_is_never_below_a_scan_of_the_ray() { let scan = |l: f64, h: f64| (0..=1000).map(|i| f64::from(i) * 0.0005).filter(|c| in_srgb(oklch_to_srgb(l, *c, h))).fold(0.0, f64::max); - assert!(max_chroma(0.02, 242.0) > 0.02, "{}", max_chroma(0.02, 242.0)); for l in [0.005, 0.02, 0.05, 0.1, 0.3, 0.44, 0.6, 0.8, 0.95, 0.99] { for h in (0..72).map(|i| f64::from(i) * 5.0 + 2.0) { let max = max_chroma(l, h); @@ -278,4 +276,16 @@ mod tests { assert_eq!(from_oklch(1.0, 0.1, 250.0), ([1.0; 3], true)); assert_eq!(from_oklch(1.0, 0.0, 0.0), ([1.0; 3], false)); } + + /// A color whose green is 0.000024 below sRGB is outside it: it is lowered to the chroma that + /// fits, not clipped at its own chroma. + #[test] + fn a_channel_just_below_zero_is_outside_the_gamut() { + assert!(!in_srgb(oklch_to_srgb(0.01, 0.01, 0.0))); + let (rgb, lowered) = from_oklch(0.01, 0.01, 0.0); + assert!(lowered, "{rgb:?}"); + let [_, c, _] = to_oklch(rgb); + assert!(c < 0.01, "{c}"); + assert!(in_srgb(oklch_to_srgb(0.01, max_chroma(0.01, 0.0), 0.0))); + } } From d1eb8c950383181a49d10ad8491a6ada477d2ede Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 26 Nov 2026 00:30:17 -0800 Subject: [PATCH 100/151] Scripts: a startup listing over the script limit keeps the first names in order The listing sorts the eligible names before it applies the limit, so the same scripts run on every launch. --- crates/engine/src/script/startup.rs | 8 ++++---- crates/engine/src/tests/script_folder.rs | 13 +++++++++++++ 2 files changed, 17 insertions(+), 4 deletions(-) diff --git a/crates/engine/src/script/startup.rs b/crates/engine/src/script/startup.rs index 17578da3ba..e20e67de3f 100644 --- a/crates/engine/src/script/startup.rs +++ b/crates/engine/src/script/startup.rs @@ -80,13 +80,13 @@ pub fn list_with(root: &Path, limits: &folder::Limits, elapsed: &mut dyn FnMut() if !kind.is_file() || kind.is_symlink() || entry.metadata().is_ok_and(|m| folder::hidden_meta(&m)) { continue; } - if names.len() >= limits.scripts { - listing.truncated = true; - continue; - } names.push(name); } names.sort_by(|a, b| (a.to_lowercase(), a).cmp(&(b.to_lowercase(), b))); + if names.len() > limits.scripts { + listing.truncated = true; + names.truncate(limits.scripts); + } listing.scripts = names.into_iter().map(|n| root.join(n)).collect(); listing } diff --git a/crates/engine/src/tests/script_folder.rs b/crates/engine/src/tests/script_folder.rs index 8ea0482826..01d84ac99f 100644 --- a/crates/engine/src/tests/script_folder.rs +++ b/crates/engine/src/tests/script_folder.rs @@ -389,3 +389,16 @@ fn the_automation_read_root_keeps_an_agent_out_of_the_scripts_folder() { }); let _ = std::fs::remove_dir_all(dir); } + +#[test] +fn a_startup_listing_over_the_script_limit_keeps_the_first_names_in_order() { + let dir = vectorcraft_testkit::TempDir::new("startup-limit"); + for name in ["d.jsx", "b.jsx", "e.jsx", "a.jsx", "c.jsx"] { + touch(&dir, name); + } + let limits = Limits { scripts: 3, ..Limits::default() }; + let listing = crate::script::startup::list_with(&dir, &limits, &mut || Duration::ZERO); + let names: Vec<_> = listing.scripts.iter().map(|p| p.file_name().unwrap().to_string_lossy().into_owned()).collect(); + assert_eq!(names, ["a.jsx", "b.jsx", "c.jsx"]); + assert!(listing.truncated); +} From 5deec7f017dc57109ab8807b8e22085b9a4e90df Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 26 Nov 2026 00:34:16 -0800 Subject: [PATCH 101/151] Scripts: the tag tests read the item they tag from pageItems, which lists the topmost first --- crates/engine/src/tests/script_tags.rs | 17 +++++++++-------- 1 file changed, 9 insertions(+), 8 deletions(-) diff --git a/crates/engine/src/tests/script_tags.rs b/crates/engine/src/tests/script_tags.rs index 5fc00f0cb0..cc477f27fa 100644 --- a/crates/engine/src/tests/script_tags.rs +++ b/crates/engine/src/tests/script_tags.rs @@ -53,7 +53,7 @@ fn tags_are_added_named_read_and_removed_in_one_undo_step() { let before = undo_steps(&s); let out = log( &mut s, - "var item = app.activeDocument.pageItems[0], tags = item.tags;\ + "var item = app.activeDocument.pageItems[1], tags = item.tags;\ vc.log(tags.typename); vc.log(tags.length);\ var t = tags.add(); vc.log(t.typename); vc.log(t.name === '' && t.value === '');\ t.name = 'size'; t.value = 'XL';\ @@ -72,7 +72,7 @@ fn tags_are_added_named_read_and_removed_in_one_undo_step() { assert!(tags(&s, a).is_empty()); s.execute("edit.redo", &json!({})).unwrap(); assert_eq!(tags(&s, a).len(), 2); - log(&mut s, "app.activeDocument.pageItems[0].tags.removeAll();"); + log(&mut s, "app.activeDocument.pageItems[1].tags.removeAll();"); assert!(tags(&s, a).is_empty()); } @@ -86,7 +86,8 @@ fn document_tags_list_every_items_tags_and_add_none() { "var d = app.activeDocument; vc.log(d.tags.length); vc.log(d.tags[0].name); vc.log(d.tags[1].name);\ vc.log(d.tags.parent.typename); vc.log(d.tags.getByName('b1').parent.typename);", ); - assert_eq!(out, [json!(2), json!("a1"), json!("b1"), json!("Document"), json!("PathItem")]); + // `pageItems` lists the topmost item first, and so does `Document.tags`. + assert_eq!(out, [json!(2), json!("b1"), json!("a1"), json!("Document"), json!("PathItem")]); // A copy keeps its source's tags. let copy = s.execute("edit.duplicate", &json!({"ids": [a.0]})).unwrap()["ids"][0].as_u64().map(NodeId).unwrap(); assert_eq!(tags(&s, copy), pairs(&[("a1", "1")])); @@ -104,13 +105,13 @@ fn bad_tag_values_throw_and_change_nothing() { let (mut s, a, _) = doc(); s.execute("object.tag.add", &json!({"id": a.0, "name": "n", "value": "v"})).unwrap(); let before = undo_steps(&s); - let tag = "app.activeDocument.pageItems[0].tags[0]"; + let tag = "app.activeDocument.pageItems[1].tags[0]"; assert!(failure(&mut s, &format!("{tag}.name = 5;")).contains("TypeError: name must be a string")); assert!(failure(&mut s, &format!("{tag}.value = null;")).contains("TypeError: value must be a string")); let long = format!("{tag}.value = new Array({}).join('x');", MAX_TAG_TEXT + 2); assert!(failure(&mut s, &long).contains("RangeError: a tag's value is longer than 65,536 bytes")); - assert!(failure(&mut s, "app.activeDocument.pageItems[0].tags.getByName('none');").contains("Not found")); - assert!(failure(&mut s, "app.activeDocument.pageItems[0].tags.index(true);").contains("TypeError")); + assert!(failure(&mut s, "app.activeDocument.pageItems[1].tags.getByName('none');").contains("Not found")); + assert!(failure(&mut s, "app.activeDocument.pageItems[1].tags.index(true);").contains("TypeError")); // A run that fails after changing a tag puts it back. assert!(failure(&mut s, &format!("{tag}.value = 'w'; throw new Error('stop');")).contains("stop")); assert_eq!(tags(&s, a), pairs(&[("n", "v")])); @@ -140,9 +141,9 @@ fn tags_work_on_an_item_and_with_tag_ids_above_2_to_the_53() { #[test] fn an_object_takes_at_most_64_tags() { let (mut s, a, _) = doc(); - let out = log(&mut s, "var t = app.activeDocument.pageItems[0].tags; for (var i = 0; i < 64; i++) t.add(); vc.log(t.length);"); + let out = log(&mut s, "var t = app.activeDocument.pageItems[1].tags; for (var i = 0; i < 64; i++) t.add(); vc.log(t.length);"); assert_eq!(out, [json!(MAX_TAGS)]); - let e = failure(&mut s, "app.activeDocument.pageItems[0].tags.add();"); + let e = failure(&mut s, "app.activeDocument.pageItems[1].tags.add();"); assert!(e.contains("64 tags"), "{e}"); assert_eq!(tags(&s, a).len(), MAX_TAGS); } From 59ab0f6c03933723c77b0a76d97335bbb1d2670e Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 26 Nov 2026 06:35:49 -0800 Subject: [PATCH 102/151] JavaScript: define the Promise prototype string tag --- crates/js/src/builtins/promise.rs | 7 ++++++- crates/js/src/promise_tests.rs | 16 ++++++++++++++++ docs/mcp.md | 2 ++ docs/target-app-parity.md | 2 ++ 4 files changed, 26 insertions(+), 1 deletion(-) diff --git a/crates/js/src/builtins/promise.rs b/crates/js/src/builtins/promise.rs index 276acf7e96..4c1b826c0e 100644 --- a/crates/js/src/builtins/promise.rs +++ b/crates/js/src/builtins/promise.rs @@ -30,7 +30,9 @@ use std::rc::Rc; use super::{arg, constructor, create_at, method, native, new_array}; use crate::LimitKind; use crate::bytecode::Code; -use crate::heap::{BOUND_ARG_BYTES, Class, Func, NativeFn, NativeKind, OBJECT_BYTES, OPEN, ObjId, Object, PROP_BYTES, Prop, Roots, key}; +use crate::heap::{ + BOUND_ARG_BYTES, CONFIGURABLE, Class, Func, NativeFn, NativeKind, OBJECT_BYTES, OPEN, ObjId, Object, PROP_BYTES, Prop, Roots, key, +}; use crate::interp::{Abrupt, ErrorType, Interp, JsResult}; use crate::string_builtins::flat_charged; use crate::value::Value; @@ -258,6 +260,9 @@ pub(crate) fn install(interp: &mut Interp) -> JsResult<()> { let object_proto = interp.intrinsics.object_proto; let proto = interp.heap.alloc_object(Object::new(Class::Ordinary, Some(object_proto))); interp.promises.proto = Some(proto); + if let Some(tag) = interp.well_known(|w| &w.to_string_tag) { + interp.define_sym(proto, tag, Prop::Data { value: Value::str("Promise"), flags: CONFIGURABLE })?; + } let ctor = native(interp, "Promise", promise_ctor, 1, NativeKind::Plain, true)?; interp.promises.ctor = Some(ctor); constructor(interp, "Promise", ctor, proto)?; diff --git a/crates/js/src/promise_tests.rs b/crates/js/src/promise_tests.rs index 915427de89..7799d63469 100644 --- a/crates/js/src/promise_tests.rs +++ b/crates/js/src/promise_tests.rs @@ -57,6 +57,22 @@ fn promise_prototype_cannot_be_replaced() { assert_eq!(string(src), "true,true,true"); } +#[test] +fn promise_prototype_has_a_configurable_string_tag() { + assert_eq!( + string( + "var d = Object.getOwnPropertyDescriptor(Promise.prototype, Symbol.toStringTag); \ + [Object.prototype.toString.call(Promise.prototype), \ + Object.prototype.toString.call(Promise.resolve()), \ + d.value, d.writable, d.enumerable, d.configurable].join()" + ), + "[object Promise],[object Promise],Promise,false,false,true" + ); + let mut r = Realm::new(); + r.add_es2015(); + assert_eq!(r.run("Object.prototype.toString.call(Promise.resolve())").unwrap(), JsValue::String("[object Promise]".into())); +} + #[test] fn then_callbacks_run_after_the_scripts_code_in_order() { let src = "Promise.resolve(1).then(function (v) { log.push('a' + v); });\n\ diff --git a/docs/mcp.md b/docs/mcp.md index 437569a1f9..b0dfeb9411 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2880,6 +2880,8 @@ In a `.js` script, `Promise` follows ECMA-262 11th edition section 25.6 `Promise.resolve`, `reject`, `all`, `allSettled` and `race`. `Promise.any` is not provided. These are VectorCraft's own rules: +- `Promise.prototype[Symbol.toStringTag]` is `"Promise"` when Symbols are available. The property is configurable, + non-enumerable and non-writable. Promise instances also report `[object Promise]` in engines without Symbols. - The callbacks `then`, `catch` and `finally` register run as jobs, one at a time, in the order they were queued, after the script's own code ends and before the run ends; a job a callback queues runs after the jobs already waiting. A promise still pending when no job is left stays pending, and the run ends. diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 043ae5c403..c0bf5036cd 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -32,6 +32,8 @@ ## Feature submission evidence +Scripts: `Promise.prototype[Symbol.toStringTag]` is `"Promise"` when Symbols are available, with a configurable, non-enumerable, non-writable descriptor. Promise instances report `[object Promise]` in engines without Symbols. Test: `promise_prototype_has_a_configurable_string_tag` in `crates/js/src/promise_tests.rs`. + Variables panel row context menus (2026-11-20, G12): Right-click highlights the clicked variable without changing the canvas selection and offers Select Bound Object, Variable Options…, Unbind Variable, the four Make Dynamic actions, and Delete Variable. Shift+F10 opens the same menu for the focused row; Escape dismisses it. Row actions target that variable; dynamic actions use the canvas selection. Lock and selection checks disable unavailable actions. Headless pointer/accessibility tests cover opening the menu, highlighting, bound-object selection, deletion in one undo step and restoration, and disabled actions. Scores and estimates unchanged. Actions panel item context menus (2026-11-20): Right-clicking an Action Set row selects it and presents a context menu with New Action…, New Set…, Duplicate Set, Delete Set, and Set Options…. Right-clicking an Action row selects it and presents a context menu with Play, Record, Duplicate, Delete, Action Options…, and Batch…. Duplicate on an action duplicates that action and selects the duplicate; Delete removes it. Headless tests in `crates/ui-egui/src/panels/actions.rs`: `right_clicking_an_action_set_selects_it_and_presents_set_context_options`, `right_clicking_an_action_selects_it_and_presents_action_options`, and `clicking_duplicate_on_an_action_duplicates_that_action_in_the_set`. Scores and estimates unchanged. From 04b20e9f53241a24f6ed47867096d9850f897d10 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 26 Nov 2026 08:17:12 -0800 Subject: [PATCH 103/151] Preserve manual leading when Block cannot fit a frame --- crates/engine/src/cmd/textstyles.rs | 8 +++-- crates/engine/src/cmd/typecmd.rs | 2 ++ crates/engine/src/cmd/typecmd/block.rs | 32 ++++++++++---------- crates/engine/src/cmd/typecmd/block_tests.rs | 16 ++++++++++ docs/mcp.md | 3 +- docs/target-app-parity.md | 2 ++ 6 files changed, 43 insertions(+), 20 deletions(-) diff --git a/crates/engine/src/cmd/textstyles.rs b/crates/engine/src/cmd/textstyles.rs index ae7c64a76b..d7657df16e 100644 --- a/crates/engine/src/cmd/textstyles.rs +++ b/crates/engine/src/cmd/textstyles.rs @@ -502,9 +502,9 @@ fn update_users(d: &mut Document, kind: Kind, name: &str, old: &Map Result { #[cfg(test)] mod area_tests; mod block; +pub(super) use block::SIZES as BLOCK_SIZES; +pub(super) use block::fit_metrics as block_fit_metrics; pub(crate) use block::needed_room; #[cfg(test)] mod block_tests; diff --git a/crates/engine/src/cmd/typecmd/block.rs b/crates/engine/src/cmd/typecmd/block.rs index c3a54ca84f..4c96d817bc 100644 --- a/crates/engine/src/cmd/typecmd/block.rs +++ b/crates/engine/src/cmd/typecmd/block.rs @@ -218,6 +218,21 @@ fn tenths(points: f64) -> f64 { ((points * 10.0 + 1e-6).floor() / 10.0).clamp(SIZES.0, SIZES.1) } +pub(crate) fn fit_metrics(t: &TextObject) -> Option<(f64, f64, f64)> { + if !t.dynamic_text { + return None; + } + let TextKind::Area { frame } = &t.kind else { return None }; + let (_, line_gap) = t.area.block_gaps(); + let b = frame.bounds().filter(|b| [b.x0, b.y0, b.x1, b.y1].iter().all(|v| v.is_finite()))?; + let points = t.style_scale().map(|s| s.points).filter(|p| p.is_finite() && *p > 1e-12)?; + let a = &t.area; + let (along, cells, gutter) = if t.vertical { (b.height(), a.rows, a.row_gutter.unwrap_or(a.gutter)) } else { (b.width(), a.columns, a.gutter) }; + let cells = cells.max(1) as f64; + let cell = (along - 2.0 * a.inset.max(0.0) - gutter.max(0.0) * (cells - 1.0)) / cells; + (cell.is_finite() && cell > 1e-9).then_some((points, line_gap, cell)) +} + /// Fit area type with Dynamic Text (Block) on: with the word gap as every paragraph's Desired word /// spacing ([`TextObject::layout_justification`]; the paragraphs keep their own values), each line /// as typed gets the size (its first character's, in steps of 0.1 pt within 0.1 to @@ -228,24 +243,9 @@ fn tenths(points: f64) -> f64 { /// has no size. A line that still wraps at its first fit is made smaller, in at most /// [`BLOCK_PASSES`] more passes. True when the text changed. pub(crate) fn block_fit(t: &mut TextObject) -> bool { - if !t.dynamic_text { - return false; - } - let TextKind::Area { frame } = &t.kind else { return false }; - let (_, line_gap) = t.area.block_gaps(); - let Some(b) = frame.bounds().filter(|b| [b.x0, b.y0, b.x1, b.y1].iter().all(|v| v.is_finite())) else { return false }; - let Some(points) = t.style_scale().map(|s| s.points).filter(|p| p.is_finite() && *p > 1e-12) else { return false }; + let Some((points, line_gap, cell)) = fit_metrics(t) else { return false }; let before = t.runs.clone(); - // The room along a line in one cell of the frame, before indents. - let a = &t.area; - let (along, cells, gutter) = if t.vertical { (b.height(), a.rows, a.row_gutter.unwrap_or(a.gutter)) } else { (b.width(), a.columns, a.gutter) }; - let cells = cells.max(1) as f64; - let cell = (along - 2.0 * a.inset.max(0.0) - gutter.max(0.0) * (cells - 1.0)) / cells; - if !(cell.is_finite() && cell > 1e-9) { - return t.runs != before; - } - let db = vectorcraft_text::FontDb::global(); let text = t.plain_text(); let lines = typed_lines(&text); diff --git a/crates/engine/src/cmd/typecmd/block_tests.rs b/crates/engine/src/cmd/typecmd/block_tests.rs index e899d1e8e5..758e011961 100644 --- a/crates/engine/src/cmd/typecmd/block_tests.rs +++ b/crates/engine/src/cmd/typecmd/block_tests.rs @@ -31,6 +31,22 @@ fn undo_len(s: &Session) -> usize { s.doc().unwrap().history.undo.len() } +#[test] +fn editing_a_character_style_keeps_manual_leading_when_block_has_no_room() { + for manual_leading in [42.0, 12.0] { + let mut s = session(); + let id = area(&mut s, 50.0, 400.0, "Inset"); + s.execute("text.areaOptions", &json!({"inset": 30})).unwrap(); + s.execute("charStyle.new", &json!({"name": "Body", "attrs": {"leading": 30}})).unwrap(); + s.execute("charStyle.apply", &json!({"name": "Body", "id": id})).unwrap(); + s.execute("text.setStyle", &json!({"ids": [id], "leading": manual_leading})).unwrap(); + s.execute("type.dynamicText", &json!({"ids": [id], "on": true})).unwrap(); + assert_eq!(text(&s, id).runs[0].style.leading, Some(manual_leading)); + s.execute("charStyle.edit", &json!({"name": "Body", "to": "Body", "attrs": {"leading": 60}})).unwrap(); + assert_eq!(text(&s, id).runs[0].style.leading, Some(manual_leading)); + } +} + /// The size of the character at `byte`. fn size_at(t: &TextObject, byte: usize) -> f64 { super::block::size_at(&t.runs, byte) diff --git a/docs/mcp.md b/docs/mcp.md index 51ffde1cab..528dd5712c 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -12053,7 +12053,8 @@ lines. The rest are VectorCraft's own rules: leading set. Otherwise each character takes its own size plus the gap, and the field is blank where those differ. `keepLineGap: true` on `text.setStyle` and `text.setRangeStyle` leaves `lineGap` as it is, and the Character panel's Reset Panel sends it, so a reset to Auto leading keeps the frame's Line Gap. Point type, type on a path and area type - with Block off keep their own leading. + with Block off keep their own leading. If Block cannot fit a frame, editing a character style keeps each run's + manual leading override. When Block can fit the frame, its generated leading follows the edited style. - The sizes are written into the characters, so every export and the Character panel see them. After every edit to the text or the frame (typing, `text.editRange`, character and paragraph changes, `text.areaOptions {width}`, a frame resize) the lines are fitted again, in the edit's own undo step. The lines are then measured again, in at diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 133a813b23..e1bbaed278 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -32,6 +32,8 @@ ## Feature submission evidence +Character-style edits keep manual leading overrides when Dynamic Text's Block cannot fit the frame. When Block can fit the frame, its generated leading follows the edited style. A regression in `crates/engine/src/cmd/typecmd/block_tests.rs` covers a frame whose inset leaves no room. + Variables panel row context menus (2026-11-20, G12): Right-click highlights the clicked variable without changing the canvas selection and offers Select Bound Object, Variable Options…, Unbind Variable, the four Make Dynamic actions, and Delete Variable. Shift+F10 opens the same menu for the focused row; Escape dismisses it. Row actions target that variable; dynamic actions use the canvas selection. Lock and selection checks disable unavailable actions. Headless pointer/accessibility tests cover opening the menu, highlighting, bound-object selection, deletion in one undo step and restoration, and disabled actions. Scores and estimates unchanged. Actions panel item context menus (2026-11-20): Right-clicking an Action Set row selects it and presents a context menu with New Action…, New Set…, Duplicate Set, Delete Set, and Set Options…. Right-clicking an Action row selects it and presents a context menu with Play, Record, Duplicate, Delete, Action Options…, and Batch…. Duplicate on an action duplicates that action and selects the duplicate; Delete removes it. Headless tests in `crates/ui-egui/src/panels/actions.rs`: `right_clicking_an_action_set_selects_it_and_presents_set_context_options`, `right_clicking_an_action_selects_it_and_presents_action_options`, and `clicking_duplicate_on_an_action_duplicates_that_action_in_the_set`. Scores and estimates unchanged. From 44f6af4d951789c2efc80ec74dc81920cd86f10d Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 26 Nov 2026 08:34:15 -0800 Subject: [PATCH 104/151] ui: hold the merge worker until pending reply checks finish --- crates/tools/Cargo.toml | 3 ++ crates/tools/src/builder.rs | 9 ++++ crates/tools/src/builder/testing.rs | 75 +++++++++++++++++++++++++++++ crates/ui-egui/Cargo.toml | 1 + crates/ui-egui/src/control/tests.rs | 37 ++++++-------- 5 files changed, 102 insertions(+), 23 deletions(-) create mode 100644 crates/tools/src/builder/testing.rs diff --git a/crates/tools/Cargo.toml b/crates/tools/Cargo.toml index 96b6a36291..a89175b05c 100644 --- a/crates/tools/Cargo.toml +++ b/crates/tools/Cargo.toml @@ -8,6 +8,9 @@ description = "VectorCraft tool state machines: pointer events in, commands and [lints] workspace = true +[features] +testing = [] + [dependencies] vectorcraft-geom = { workspace = true } vectorcraft-color = { workspace = true } diff --git a/crates/tools/src/builder.rs b/crates/tools/src/builder.rs index cec57b2887..cdc7f6f7dc 100644 --- a/crates/tools/src/builder.rs +++ b/crates/tools/src/builder.rs @@ -33,6 +33,9 @@ mod live_paint; mod lookup; mod map; +#[cfg(all(feature = "testing", not(target_arch = "wasm32")))] +pub mod testing; + use cache::{BACKGROUND_SEGMENTS, CacheKey, RegionCache}; pub use fill_area::{AreaFinder, EnclosedArea, FillAreaTool, every_layer, fill_area_roots}; #[cfg(test)] @@ -260,7 +263,13 @@ struct PendingMerge { #[cfg(not(target_arch = "wasm32"))] fn spawn_merge(map: Arc, touched: Touched, gap: f64, inputs: Vec) -> Option> { let (tx, done) = std::sync::mpsc::channel(); + #[cfg(feature = "testing")] + let gate = testing::take(); let spawned = std::thread::Builder::new().name("vectorcraft-shape-builder-merge".into()).spawn(move || { + #[cfg(feature = "testing")] + if let Some(gate) = gate { + gate.wait(); + } // The tool may have dropped the receiver meanwhile (another tool, another document). let _ = tx.send(merge_geometry(&map, &touched, gap, &inputs)); }); diff --git a/crates/tools/src/builder/testing.rs b/crates/tools/src/builder/testing.rs new file mode 100644 index 0000000000..a378014e32 --- /dev/null +++ b/crates/tools/src/builder/testing.rs @@ -0,0 +1,75 @@ +//! Channel control for the next Shape Builder merge started on the calling thread. + +use std::cell::RefCell; +use std::marker::PhantomData; +use std::rc::Rc; +use std::sync::Arc; +use std::sync::mpsc::{Receiver, RecvError, Sender, channel}; + +thread_local! { + static NEXT: RefCell> = const { RefCell::new(None) }; +} + +/// Holds a merge worker until released. Dropping the gate also releases the worker. +pub struct MergeGate { + id: Arc<()>, + started: Receiver<()>, + release: Option>, + _thread: PhantomData>, +} + +impl MergeGate { + /// Waits until the worker reaches the gate. + pub fn wait_started(&self) -> Result<(), RecvError> { + self.started.recv() + } + + /// Allows the worker to compute the merge. + pub fn release(&mut self) { + if let Some(release) = self.release.take() { + let _ = release.send(()); + } + } +} + +impl Drop for MergeGate { + fn drop(&mut self) { + NEXT.with_borrow_mut(|next| { + if next.as_ref().is_some_and(|gate| Arc::ptr_eq(&gate.id, &self.id)) { + *next = None; + } + }); + self.release(); + } +} + +pub(super) struct WorkerGate { + id: Arc<()>, + started: Sender<()>, + release: Receiver<()>, +} + +impl WorkerGate { + pub(super) fn wait(self) { + let _ = self.started.send(()); + let _ = self.release.recv(); + } +} + +pub(super) fn take() -> Option { + NEXT.with_borrow_mut(Option::take) +} + +/// Pauses the next merge started on this thread. Returns an error if a gate is already waiting. +pub fn pause_next_merge() -> Result { + NEXT.with_borrow_mut(|next| { + if next.is_some() { + return Err("a Shape Builder merge gate is already waiting on this thread"); + } + let id = Arc::new(()); + let (started_tx, started) = channel(); + let (release, release_rx) = channel(); + *next = Some(WorkerGate { id: id.clone(), started: started_tx, release: release_rx }); + Ok(MergeGate { id, started, release: Some(release), _thread: PhantomData }) + }) +} diff --git a/crates/ui-egui/Cargo.toml b/crates/ui-egui/Cargo.toml index 154afe235d..95487e91c0 100644 --- a/crates/ui-egui/Cargo.toml +++ b/crates/ui-egui/Cargo.toml @@ -101,6 +101,7 @@ egui_kittest = { workspace = true, features = ["wgpu", "snapshot"] } egui_extras = { workspace = true } vectorcraft-apischema = { workspace = true } vectorcraft-testkit = { workspace = true } +vectorcraft-tools = { workspace = true, features = ["testing"] } # A variable font built in code (no font file is committed). vectorcraft-text = { workspace = true, features = ["test-fonts"] } wat = { workspace = true } diff --git a/crates/ui-egui/src/control/tests.rs b/crates/ui-egui/src/control/tests.rs index e7e617a74e..f895671b1f 100644 --- a/crates/ui-egui/src/control/tests.rs +++ b/crates/ui-egui/src/control/tests.rs @@ -912,6 +912,7 @@ fn pointer_replies_name_the_key_object() { /// A Shape Builder click on a large selection merges on another thread: the frames go on, and /// the `ui.pointer` reply comes once the merge is applied, with the selection after it. +#[cfg(not(target_arch = "wasm32"))] #[test] fn pointer_reply_waits_for_a_merge_on_another_thread() { let (tx, rx) = std::sync::mpsc::channel(); @@ -933,7 +934,9 @@ fn pointer_reply_waits_for_a_merge_on_another_thread() { assert_eq!(hover.try_recv().unwrap()["ok"], true, "a hover is answered at once"); app.session.tool_poll(app.view_info(), true).unwrap(); let revision = app.session.active().unwrap().revision; + let mut merge = vectorcraft_tools::builder::testing::pause_next_merge().unwrap(); let click = send(&mut app, json!([{"kind": "down", "x": 15, "y": 10}, {"kind": "up", "x": 15, "y": 10}])); + merge.wait_started().unwrap(); assert!(click.try_recv().is_err() && app.session.tool_editing(), "the click is not answered before the merge is applied"); // A hover sent meanwhile is answered at once; a click is made after the merge, and its // reply waits until then. @@ -944,32 +947,20 @@ fn pointer_reply_waits_for_a_merge_on_another_thread() { assert!(press.try_recv().is_err(), "a Cmd-click during the merge waits for it"); let hover = send(&mut app, json!([{"kind": "move", "x": 45, "y": 10}])); assert_eq!(hover.try_recv().map(|r| r["ok"].clone()), Ok(json!(true)), "a hover after the held Cmd-click"); - let start = std::time::Instant::now(); - let reply = loop { - if let Ok(r) = click.try_recv() { - break r; - } - assert!(app.session.tool_editing(), "the merge is being computed until the reply goes"); - assert_eq!(app.session.active().unwrap().revision, revision); - assert!(start.elapsed() < std::time::Duration::from_secs(60), "no reply"); - std::thread::sleep(std::time::Duration::from_millis(2)); - // A frame: the canvas checks on the tool, then the replies are answered. - let r = app.session.tool_poll(app.view_info(), false); - crate::canvas::apply_requests(&mut app, r); - app.run_control(&ctx); - }; + assert!(app.session.tool_editing(), "the merge is being computed until the reply goes"); + assert_eq!(app.session.active().unwrap().revision, revision); + merge.release(); + let r = app.session.tool_poll(app.view_info(), true); + crate::canvas::apply_requests(&mut app, r); + app.run_control(&ctx); + let reply = click.try_recv().expect("the merge was applied before answering the click"); assert_eq!(reply["ok"], true, "{reply}"); assert_eq!(reply["result"]["selection"].as_array().map(Vec::len), Some(41), "{reply}: the selection after the merge"); assert_ne!(app.session.active().unwrap().revision, revision); - let press = loop { - if let Ok(r) = press.try_recv() { - break r; - } - assert!(start.elapsed() < std::time::Duration::from_secs(60), "no reply to the Cmd-click"); - let r = app.session.tool_poll(app.view_info(), false); - crate::canvas::apply_requests(&mut app, r); - app.run_control(&ctx); - }; + let r = app.session.tool_poll(app.view_info(), true); + crate::canvas::apply_requests(&mut app, r); + app.run_control(&ctx); + let press = press.try_recv().expect("the held Cmd-click was applied after the merge"); assert_eq!(press["result"]["selection"].as_array().map(Vec::len), Some(0), "{press}: the lent selection tool deselected after the merge"); assert_eq!(press["result"]["tool"], "shapeBuilder", "{press}"); } From 6b246b306d2d6dd3646c40696615de9363b15a5c Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 26 Nov 2026 08:43:42 -0800 Subject: [PATCH 105/151] Keep late loads out of a reopened Proof Setup dialog --- crates/ui-egui/src/dialogs/proof_setup.rs | 49 ++++++++++++++++++++--- 1 file changed, 44 insertions(+), 5 deletions(-) diff --git a/crates/ui-egui/src/dialogs/proof_setup.rs b/crates/ui-egui/src/dialogs/proof_setup.rs index b4982f3710..a5987f699b 100644 --- a/crates/ui-egui/src/dialogs/proof_setup.rs +++ b/crates/ui-egui/src/dialogs/proof_setup.rs @@ -17,7 +17,7 @@ //! `intent`, `simulatePaper`, `simulateBlack` and `preview`. use std::path::{Path, PathBuf}; -use std::sync::{Mutex, MutexGuard}; +use std::sync::{Arc, Mutex, MutexGuard}; use craft::host::queue::{JobQueue, Priority, QueueOptions}; use craft::host::{PickRequest, Picked, Wake}; @@ -32,7 +32,7 @@ use vectorcraft_render::proof; use super::host::{HeldOptions, open_held_with}; use crate::VectorcraftApp; -use crate::file_asks::{Owner, ask}; +use crate::file_asks::{Owner, ask, ask_while}; use crate::menus::Node; /// The dialog kind of Proof Setup › Customize. @@ -53,6 +53,8 @@ const LOAD_BUTTON: &str = "load"; pub(crate) struct Open { /// The dialog on the window's stack. id: DialogId, + /// The identity of this opening, since Proof Setup reuses the dialog ID. + opening: Arc<()>, /// The proof view the dialog found, which Cancel puts back after a preview. before: proof::ProofView, /// The proof view the preview last put on the canvas; `None` while no preview of this dialog is shown. @@ -89,7 +91,7 @@ pub fn open(app: &mut VectorcraftApp) { let dialog = HostedParamDialog::new(&ctx, KIND, fields, build); let options = HeldOptions { cancel: Some(Box::new(cancel)), ..Default::default() }; match open_held_with(app, dialog, |app, result: &ParamResult| confirm(app, &result.fields), options) { - Some(id) => app.ui.proof_setup = Some(Open { id, before, shown: None, sent: None }), + Some(id) => app.ui.proof_setup = Some(Open { id, opening: Arc::new(()), before, shown: None, sent: None }), None => app.status(tl!("There is no window to show Proof Setup in.")), } } @@ -330,12 +332,17 @@ fn save(app: &mut VectorcraftApp, fields: &DialogFields) { /// Load…: the picked file's settings fill the dialog `id` (Preview then shows them). fn load(app: &mut VectorcraftApp, id: DialogId) { + let Some(opening) = app.ui.proof_setup.as_ref().filter(|open| open.id == id).map(|open| Arc::clone(&open.opening)) else { return }; let mut request = PickRequest::open("proof-setups").filter("Proof setups", &[EXT]); // Before a setup is saved there is no folder, and the picker starts in its own default folder. if let Some(dir) = app.session.proof_setup_dir().filter(|dir| dir.is_dir()) { request = request.directory(dir); } - ask(app, request, Owner::Free, move |app, picked| { + let is_live = move |app: &VectorcraftApp| { + app.ui.proof_setup.as_ref().is_some_and(|open| open.id == id && Arc::ptr_eq(&opening, &open.opening)) + && app.dialogs().is_some_and(|dialogs| dialogs.with(|host| host.get_by_id::(id).is_some())) + }; + ask_while(app, request, Owner::Free, is_live, move |app, picked| { let Some(path) = picked.first_path() else { return Ok(Value::Null) }; let r = app.run("view.proofSetup.read", json!({ "path": path.to_string_lossy() }))?; let fields = [ @@ -345,7 +352,6 @@ fn load(app: &mut VectorcraftApp, id: DialogId) { ("simulatePaper", "simulatePaper"), ("simulateBlack", "simulateBlack"), ]; - // The dialog may have closed while the picker was open: then there is nothing to fill. // PLAN: sh.K23's `set_json_fields` refuses a row that is disabled by the file's own device (an RGB // device disables paper and black ink), so the whole load would fail; the values are set unchecked. if let Some(dialogs) = app.dialogs() { @@ -811,6 +817,39 @@ mod tests { assert_eq!((v.setup.target, v.setup.intent), (ProofTarget::Rgb(cms::DISPLAY_P3.into()), Intent::Saturation)); } + #[test] + fn a_delayed_load_only_changes_the_proof_setup_that_requested_it() { + let _view = DefaultProofView::new(); + let (mut app, ctx) = app(); + let dir = vectorcraft_testkit::TempDir::new("proof-setup-delayed-load"); + let file = dir.join(format!("Pending.{EXT}")); + app.run("view.proofSetup.save", json!({"path": file.to_string_lossy(), "target": WORKING, "intent": "saturation"})).unwrap(); + let files = scripted(&mut app, ScriptedFiles::held()); + app.run("ui.proofSetupDialog", json!({})).unwrap(); + press(&mut app, &ctx, LOAD_BUTTON); + assert_eq!(files.requests().len(), 1, "Load requested a file"); + cancel_dialog(&mut app, &ctx); + app.run("ui.proofSetupDialog", json!({})).unwrap(); + set(&mut app, &ctx, "intent", json!("perceptual")); + set(&mut app, &ctx, "preview", json!(true)); + let view = proof::view(); + + files.answer(Picked::Paths(vec![file.clone()])); + crate::file_asks::poll(&mut app); + pump(&mut app, &ctx); + assert_eq!(values(&app)["intent"], "perceptual", "the reopened dialog keeps its own rendering intent"); + assert_eq!(proof::view(), view, "the reopened dialog keeps its own proof preview"); + + press(&mut app, &ctx, LOAD_BUTTON); + assert_eq!(files.requests().len(), 2, "Load in the current opening requested a file"); + files.answer(Picked::Paths(vec![file])); + crate::file_asks::poll(&mut app); + pump(&mut app, &ctx); + assert_eq!(values(&app)["intent"], "saturation", "a reply to the current opening fills the dialog"); + assert_eq!(proof::view().setup.intent, Intent::Saturation, "the current opening previews the loaded setup"); + cancel_dialog(&mut app, &ctx); + } + /// Save… whose picker is canceled saves nothing and leaves no Proof Setups folder behind; the /// folder stays while the picker is open and when a file is saved in it. #[test] From 0f4d83469e8f8e4c71827f7b1880c85df2f0091a Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 26 Nov 2026 08:45:02 -0800 Subject: [PATCH 106/151] Leave the current document active when a cancelled Graph Data picker answers --- crates/ui-egui/src/dialogs/graph_data.rs | 38 +++++++++++++++++++++++- 1 file changed, 37 insertions(+), 1 deletion(-) diff --git a/crates/ui-egui/src/dialogs/graph_data.rs b/crates/ui-egui/src/dialogs/graph_data.rs index 572f92f664..ffcc511501 100644 --- a/crates/ui-egui/src/dialogs/graph_data.rs +++ b/crates/ui-egui/src/dialogs/graph_data.rs @@ -460,7 +460,18 @@ pub(crate) fn pump(app: &mut VectorcraftApp, _ctx: &egui::Context) { Action::Import => { let request = PickRequest::open("document").filter("Text", &["txt", "tsv", "csv"]); let owner = import_owner.clone(); - file_asks::ask(app, request, Owner::Document, move |app, picked| import(app, &owner, picked)); + let current = import_owner.clone(); + file_asks::ask_while( + app, + request, + Owner::Document, + move |app| { + app.dialogs().is_some_and(|dialogs| { + dialogs.with(|host| host.get::().is_some_and(|d| Arc::ptr_eq(&d.import_owner, ¤t))) + }) + }, + move |app, picked| import(app, &owner, picked), + ); } Action::Revert => match graph_grid(app, graph) { Ok(grid) => { @@ -998,6 +1009,31 @@ mod tests { assert_eq!(series(&h), "imported"); } + #[test] + fn graph_data_import_does_not_reactivate_the_document_of_a_closed_sheet() { + let (mut app, _) = app_with(",first\nQ1,1", "column"); + let picker = crate::tests::picks::scripted(&mut app); + let ctx = app.ui_ctx.as_ref().unwrap().clone(); + let first = app.session.active().unwrap().uid; + open(&mut app).unwrap(); + edit(&app, |d| d.actions.push(Action::Import)); + pump(&mut app, &ctx); + assert_eq!(picker.requests().len(), 1); + + app.dialogs().unwrap().with(|host| host.cancel::(&ctx)); + app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); + app.run("graph.create", json!({"type": "column", "x": 20, "y": 20, "width": 100, "height": 100, "csv": ",second\nQ2,2"})).unwrap(); + let second = app.session.active().unwrap().uid; + assert_ne!(first, second); + assert_eq!(app.session.documents().len(), 2); + open(&mut app).unwrap(); + + picker.answer_contents(&[("first.txt", b"\tstale\nQ1\t7")]); + file_asks::poll(&mut app); + assert_eq!(app.session.active().unwrap().uid, second); + assert_eq!(read(&app, |d| cell_of(&d.sheet.grid, 0, 1)), "second"); + } + #[test] fn transpose_and_switch_xy() { assert_eq!(transpose(&g(&[&["", "a", "b"], &["Q1", "1", "2"]])), g(&[&["", "Q1"], &["a", "1"], &["b", "2"]])); From 374e79fd5732643faaa7eab50f7c94155721d865 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 26 Nov 2026 08:29:44 -0800 Subject: [PATCH 107/151] Bind imported preset selection to the requesting manager --- crates/ui-egui/src/dialogs/pdf_presets.rs | 27 ++++++++++++++++++++ crates/ui-egui/src/dialogs/preset_manager.rs | 23 ++++++++++++----- 2 files changed, 43 insertions(+), 7 deletions(-) diff --git a/crates/ui-egui/src/dialogs/pdf_presets.rs b/crates/ui-egui/src/dialogs/pdf_presets.rs index e0e68d0eda..4e36bbaddc 100644 --- a/crates/ui-egui/src/dialogs/pdf_presets.rs +++ b/crates/ui-egui/src/dialogs/pdf_presets.rs @@ -220,6 +220,33 @@ mod tests { assert!(!manager_open(&app), "Close"); } + #[test] + fn a_late_preset_import_keeps_the_reopened_managers_selection() { + let mut app = app(); + let picker = crate::tests_picks::scripted(&mut app); + app.run("pdf.preset.save", json!({"name": "Mine", "thumbnails": true})).unwrap(); + let exported = app.run("pdf.preset.export", json!({"names": ["Mine"]})).unwrap(); + let bytes = exported["data"].as_str().unwrap().as_bytes(); + + open(&mut app, Some("PDF/X-4:2010")); + press(&mut app, ManagerAction::Import); + assert_eq!(picker.requests().len(), 1, "Import requested a file"); + host(&app, |h| h.cancel_by_id(&ctx(&app), dialog_id(KEY))); + open(&mut app, Some("Press Quality")); + let ctx = ctx(&app); + picker.answer_contents(&[("mine.vcpdfpresets", bytes)]); + crate::tests_picks::poll(&mut app, &ctx); + frame(&mut app); + assert!(app.session.prefs.pdf_presets.iter().any(|preset| preset.name == "Mine 2"), "the late reply still imports: {}", app.ui.status); + assert_eq!(manager_fields(&mut app)["selected"], "Press Quality"); + + press(&mut app, ManagerAction::Import); + picker.answer_contents(&[("mine.vcpdfpresets", bytes)]); + crate::tests_picks::poll(&mut app, &ctx); + frame(&mut app); + assert_eq!(manager_fields(&mut app)["selected"], "Mine 3", "the original manager selects its own import"); + } + #[test] fn import_and_export_go_through_files() { let dir = std::env::temp_dir().join(format!("vc-pdfpresets-ui-{}", std::process::id())); diff --git a/crates/ui-egui/src/dialogs/preset_manager.rs b/crates/ui-egui/src/dialogs/preset_manager.rs index 319d3a49b3..ed62539226 100644 --- a/crates/ui-egui/src/dialogs/preset_manager.rs +++ b/crates/ui-egui/src/dialogs/preset_manager.rs @@ -160,8 +160,8 @@ pub(crate) fn above(saved: Option, built_ins: usize) -> usize { (saved.unwrap_or(0) + built_ins).saturating_sub(1) } -/// Ask for a preset file and run `command` on it, then select the first preset it imported in the open manager -/// `key`. Returns at once: the answer arrives later. +/// Ask for a preset file and run `command` on it. Select the first imported preset if the manager +/// that opened the picker is still open. pub(crate) fn import( app: &mut VectorcraftApp, key: &'static str, @@ -169,14 +169,20 @@ pub(crate) fn import( filter: &str, exts: &[&str], ) -> Result, String> { - // PLAN: assumed `file_asks::open_params(&Picked) -> Option>` (fl.A23) also names a picked file - // of the web, which the import commands may not read yet. + let id = dialog_id(key); + let opening = with_manager(app, id, |manager| Arc::clone(&manager.opening)); let request = PickRequest::open(key).filter(filter, exts); file_asks::ask(app, request, Owner::Free, move |app, picked| { - let params = file_asks::open_params(&picked).ok_or("cancelled")?; + let mut params = file_asks::open_params(&picked).ok_or("cancelled")?; + // Preset import commands take the file contents without the browser's suggested name. + params.remove("name"); let imported = app.run(command, Value::Object(params))?; - if let Some(first) = imported["imported"].get(0).and_then(Value::as_str) { - with_manager(app, dialog_id(key), |manager| manager.selected = first.to_owned()); + if let (Some(opening), Some(first)) = (opening, imported["imported"].get(0).and_then(Value::as_str)) { + with_manager(app, id, |manager| { + if Arc::ptr_eq(&opening, &manager.opening) { + manager.selected = first.to_owned(); + } + }); } Ok(imported) }); @@ -220,6 +226,8 @@ fn with_manager(app: &VectorcraftApp, id: DialogId, f: impl FnOnce(&mut Prese /// A preset manager dialog: draws the rows and the detail it holds and queues the user's events. pub(crate) struct PresetManager { id: DialogId, + /// Distinguishes successive openings that share the same dialog ID. + opening: Arc<()>, source: &'static Source, title: Label, rows: Vec, @@ -237,6 +245,7 @@ impl PresetManager { fn new(source: &'static Source, rows: Vec, selected: String, stored: Value, detail: Vec) -> Self { let mut manager = PresetManager { id: dialog_id(source.key), + opening: Arc::new(()), source, title: Label::from((source.title)()), rows: Vec::new(), From 7da21d015ccfb552124fd244315e9da5b28724c8 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 26 Nov 2026 08:56:39 -0800 Subject: [PATCH 108/151] Validate and retain chosen scripts before startup runs --- crates/engine/src/cmd/scripts.rs | 24 +++++++++---- crates/engine/src/lib.rs | 1 + crates/engine/src/script/mod.rs | 2 ++ crates/engine/src/session/documents.rs | 1 + crates/engine/tests/script_startup.rs | 50 ++++++++++++++++++++++++++ docs/mcp.md | 4 ++- docs/target-app-parity.md | 2 ++ 7 files changed, 77 insertions(+), 7 deletions(-) diff --git a/crates/engine/src/cmd/scripts.rs b/crates/engine/src/cmd/scripts.rs index 2bade13aa5..d92f654888 100644 --- a/crates/engine/src/cmd/scripts.rs +++ b/crates/engine/src/cmd/scripts.rs @@ -95,7 +95,7 @@ pub fn specs() -> Vec { "Run Startup Scripts", [], None, - "{reason: launch|menu (launch: the app starting; menu: before a script chosen from File › Scripts), then?: script.run's parameters (the script to run once the startup scripts have run), maxFuel?: whole number from 1 to 100000000000 (each startup script's instructions; default 1000000000)} run the .jsx files of the Startup Scripts folder next to the settings, one at a time, as script.run runs a file, each with the same limits as any script and its own undo step; nothing runs, and the reply says why, when the runStartupScripts preference is off (the default), in Safe Mode, or in a session without the folder (the web, and a run with VECTORCRAFT_NO_PREFS); only the folder's own .jsx files run, sorted by name without regard to case, then by name; links, hidden files, names starting with a dot, subfolders and other files are left out, and so is a script the Safe Mode choice disabled; a missing folder runs nothing; a script that cannot be read, is larger than 8 MiB, fails or is stopped is named in failed and in the Script Console, and the next one runs, then the script of then; while a startup script runs, the launch marker names it, so a launch that stops there offers to disable it; script.* commands are refused inside a script, so a startup script does not start another startup run. VectorCraft's own rules: the folder, the order, the limits of a listing (2048 folder entries, 512 scripts, 250 ms) and what a failure does → {reason, skipped: true, why: off|safeMode|noFolder, then?: script.run's reply} | {reason, skipped: false, ran: [names], failed: [{name, error}], disabled: [names], truncated, unreadable, then?: script.run's reply}, or, in the app, {reason, skipped: false, running, queued: the runs queued, then's included, failed: [{name, error}] (the runs that could not start before the first one did), disabled, truncated, unreadable, then?: script.run's reply when it ran to its end at once}, each run then reporting as script.run's do, and a later run that cannot start is named in the status bar, where the message of a startup script that fails or is stopped also stays", + "{reason: launch|menu (launch: the app starting; menu: before a script chosen from File › Scripts), then?: script.run's parameters (the script to run once the startup scripts have run; its source is read once and must compile before enabled startup scripts run), maxFuel?: whole number from 1 to 100000000000 (each startup script's instructions; default 1000000000)} run the .jsx files of the Startup Scripts folder next to the settings, one at a time, as script.run runs a file, each with the same limits as any script and its own undo step; nothing runs, and the reply says why, when the runStartupScripts preference is off (the default), in Safe Mode, or in a session without the folder (the web, and a run with VECTORCRAFT_NO_PREFS); only the folder's own .jsx files run, sorted by name without regard to case, then by name; links, hidden files, names starting with a dot, subfolders and other files are left out, and so is a script the Safe Mode choice disabled; a missing folder runs nothing; a script that cannot be read, is larger than 8 MiB, fails or is stopped is named in failed and in the Script Console, and the next one runs, then the script of then; while a startup script runs, the launch marker names it, so a launch that stops there offers to disable it; script.* commands are refused inside a script, so a startup script does not start another startup run. VectorCraft's own rules: the folder, the order, the limits of a listing (2048 folder entries, 512 scripts, 250 ms) and what a failure does → {reason, skipped: true, why: off|safeMode|noFolder, then?: script.run's reply} | {reason, skipped: false, ran: [names], failed: [{name, error}], disabled: [names], truncated, unreadable, then?: script.run's reply}, or, in the app, {reason, skipped: false, running, queued: the runs queued, then's included, failed: [{name, error}] (the runs that could not start before the first one did), disabled, truncated, unreadable, then?: script.run's reply when it ran to its end at once}, each run then reporting as script.run's do, and a later run that cannot start is named in the status bar, where the message of a startup script that fails or is stopped also stays", always, startup_run ), @@ -159,6 +159,10 @@ pub const TOO_LARGE: &str = "the script is too large to run"; fn run(s: &mut Session, p: &Value) -> Result { let request = prepare(s, p)?; + run_prepared(s, request) +} + +fn run_prepared(s: &mut Session, request: script::Request) -> Result { let name = s.script_start(request)?; if s.script_frames { return Ok(json!({"running": true, "name": name})); @@ -474,7 +478,11 @@ impl Session { } } script::startup::Queued::Then(params) => { - match scope.clone().run(|| run(self, ¶ms)) { + let prepared = self.script_queue_then.take(); + match scope.clone().run(|| match prepared { + Some(request) => run_prepared(self, request), + None => run(self, ¶ms), + }) { Ok(_) if self.script_key.is_some() => {} Ok(v) => reply = Some(v), Err(e) => self.startup_failures.push((then_name(¶ms), e.to_string())), @@ -485,6 +493,7 @@ impl Session { } if queue.is_empty() { self.script_queue_scope = None; + self.script_queue_then = None; } self.script_queue = queue; reply @@ -561,8 +570,10 @@ fn startup_run(s: &mut Session, p: &Value) -> Result { return Ok(out); } }; - if let Some(then) = &then { - prepare(s, then)?; + let prepared = then.as_ref().map(|params| prepare(s, params)).transpose()?; + if let Some(request) = &prepared { + let mut preflight = Session::new(); + preflight.script_start(request.clone())?; } let folder = root.to_string_lossy().into_owned(); // The folder is the app's: a refusal names it as the request may see it. @@ -576,6 +587,7 @@ fn startup_run(s: &mut Session, p: &Value) -> Result { s.script_queue = scripts.into_iter().map(|path| script::startup::Queued::Startup { path, fuel }).chain(then.map(script::startup::Queued::Then)).collect(); s.script_queue_scope = Some(crate::file_access::ScopeHandle::capture()); + s.script_queue_then = prepared; let queued = s.script_queue.len(); s.startup_failures.clear(); let then = s.start_queued(); @@ -612,8 +624,8 @@ fn startup_run(s: &mut Session, p: &Value) -> Result { "truncated": listing.truncated, "unreadable": listing.unreadable, }); - if let Some(then) = then { - out["then"] = run(s, &then)?; + if let Some(request) = prepared { + out["then"] = run_prepared(s, request)?; } Ok(out) } diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 7e97c28337..90086cc6a1 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -347,6 +347,7 @@ pub struct Session { /// The file access scope of the request that queued [`Self::script_queue`], in which each queued /// run starts and is read. pub(crate) script_queue_scope: Option, + pub(crate) script_queue_then: Option, /// While a startup script runs: the launch marker's entry naming it /// ([`vectorcraft_plugins::safe_mode::loading`]). pub(crate) startup_loading: Option, diff --git a/crates/engine/src/script/mod.rs b/crates/engine/src/script/mod.rs index dbb24b641a..55c5ebcd1a 100644 --- a/crates/engine/src/script/mod.rs +++ b/crates/engine/src/script/mod.rs @@ -187,6 +187,7 @@ pub(crate) fn refused_text(id: &str) -> String { } /// A request to run a script. +#[derive(Clone)] pub(crate) struct Request { /// The run's name; unless `name_given`, a `#script` line in the script replaces it. pub name: String, @@ -1951,6 +1952,7 @@ impl Session { let queued = !self.script_queue.is_empty(); self.script_queue.clear(); self.script_queue_scope = None; + self.script_queue_then = None; self.startup_ended(); let Some(key) = self.script_key.take() else { return queued }; let Some(job) = JOBS.with(|jobs| jobs.borrow_mut().remove(&key.id)) else { diff --git a/crates/engine/src/session/documents.rs b/crates/engine/src/session/documents.rs index 6c1a0b408c..691c0b552d 100644 --- a/crates/engine/src/session/documents.rs +++ b/crates/engine/src/session/documents.rs @@ -180,6 +180,7 @@ impl Session { script_frames: false, script_queue: Default::default(), script_queue_scope: None, + script_queue_then: None, startup_loading: None, startup_failures: vec![], script_high_water: Default::default(), diff --git a/crates/engine/tests/script_startup.rs b/crates/engine/tests/script_startup.rs index f6f423da89..24c14113de 100644 --- a/crates/engine/tests/script_startup.rs +++ b/crates/engine/tests/script_startup.rs @@ -293,6 +293,56 @@ fn a_chosen_script_that_cannot_start_is_refused_before_any_startup_script_runs() } } +#[test] +fn a_chosen_script_with_invalid_syntax_is_refused_before_startup_scripts_run() { + let _f = fresh(); + let dir = tmp_dir("invalid-chosen-syntax"); + write(&dir, "a.jsx", "vc.log('startup ran');"); + for frames in [false, true] { + let mut s = session(&dir); + s.script_frames = frames; + let result = s.execute("script.startup.run", &json!({"reason": "menu", "then": {"source": "var = ;"}})); + assert!(result.is_err(), "frames={frames}: {result:?}"); + assert!(!s.script_running()); + assert!(started(&s).is_empty(), "no startup script ran, frames={frames}"); + assert!(s.take_startup_failures().is_empty()); + } +} + +#[test] +fn an_installed_chosen_script_runs_the_text_read_before_startup_scripts() { + let _f = fresh(); + for frames in [false, true] { + let dir = tmp_dir(if frames { "chosen-snapshot-sliced" } else { "chosen-snapshot-sync" }); + let data = dir.join("data"); + let startup = dir.join("startup"); + let entry = write(&startup, "a.jsx", ""); + let real = std::fs::canonicalize(&entry).unwrap(); + let key = vectorcraft_plugins::permissions::sha256_hex(real.to_string_lossy().as_bytes()); + let installed = data.join(&key[..16]); + let chosen = write(&installed, "chosen.jsx", "vc.log('chosen');"); + let quoted = serde_json::to_string(&chosen.to_string_lossy()).unwrap(); + write(&startup, "a.jsx", &format!("Folder.userData; if (!new File({quoted}).remove()) throw 'remove failed';")); + let mut s = session(&startup); + s.attach_script_data(data); + s.attach_scripts_dir(installed); + s.script_frames = frames; + s.execute("script.startup.run", &json!({"reason": "menu", "then": {"path": chosen, "installed": true}})).unwrap(); + for _ in 0..10_000 { + if !s.script_running() { + break; + } + if let Some(result) = s.script_pump() { + result.unwrap(); + } + } + assert!(!s.script_running()); + assert!(s.take_startup_failures().is_empty()); + assert_eq!(started(&s), ["a.jsx", "chosen.jsx"]); + assert!(!chosen.exists()); + } +} + #[test] fn in_the_app_a_stopped_startup_script_keeps_its_report_until_the_next_pump_starts_the_queued_run() { let _f = fresh(); diff --git a/docs/mcp.md b/docs/mcp.md index f41713a2fd..dd40240774 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -3498,7 +3498,9 @@ The rest of this section is VectorCraft's own rules: `script.startup.run {reason: launch|menu, then?, maxFuel?}` runs the folder now. `then` holds `script.run`'s parameters for a script that runs after the startup scripts. A `then` that `script.run` would refuse, such as a -missing file or one larger than 8 MiB, ends the request with `script.run`'s error before any startup script runs. +missing file, one larger than 8 MiB, or source that fails to compile, ends the request with `script.run`'s error +before any startup script runs. Compilation does not execute the chosen script. The chosen script runs the source +read before startup scripts begin, including when a startup script removes the installed file. `maxFuel` limits each startup script's instructions (from 1 to 100,000,000,000, default 1,000,000,000). It returns `{reason, skipped: true, why}` with `why` set to `off`, `safeMode` or `noFolder` when nothing runs, and otherwise `{reason, skipped: false, ran, failed: [{name, error}], diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 3a8fcd7b48..ef4b0166d0 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -32,6 +32,8 @@ ## Feature submission evidence +When startup scripts precede a chosen script, its source must compile before startup scripts run. Invalid chosen source is rejected before startup scripts execute in synchronous and sliced sessions. The chosen script runs the source read before startup scripts, including when a startup script removes its installed file. `crates/engine/tests/script_startup.rs` covers both modes. + Variables panel row context menus (2026-11-20, G12): Right-click highlights the clicked variable without changing the canvas selection and offers Select Bound Object, Variable Options…, Unbind Variable, the four Make Dynamic actions, and Delete Variable. Shift+F10 opens the same menu for the focused row; Escape dismisses it. Row actions target that variable; dynamic actions use the canvas selection. Lock and selection checks disable unavailable actions. Headless pointer/accessibility tests cover opening the menu, highlighting, bound-object selection, deletion in one undo step and restoration, and disabled actions. Scores and estimates unchanged. Actions panel item context menus (2026-11-20): Right-clicking an Action Set row selects it and presents a context menu with New Action…, New Set…, Duplicate Set, Delete Set, and Set Options…. Right-clicking an Action row selects it and presents a context menu with Play, Record, Duplicate, Delete, Action Options…, and Batch…. Duplicate on an action duplicates that action and selects the duplicate; Delete removes it. Headless tests in `crates/ui-egui/src/panels/actions.rs`: `right_clicking_an_action_set_selects_it_and_presents_set_context_options`, `right_clicking_an_action_selects_it_and_presents_action_options`, and `clicking_duplicate_on_an_action_duplicates_that_action_in_the_set`. Scores and estimates unchanged. From 50e244c3b3e1d23440faf75b56cf31d651b2258c Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 26 Nov 2026 09:00:22 -0800 Subject: [PATCH 109/151] Let the keyboard select linked JavaScript files --- .../ui-egui/src/dialogs/javascript_files.rs | 38 ++++++++++++++----- 1 file changed, 29 insertions(+), 9 deletions(-) diff --git a/crates/ui-egui/src/dialogs/javascript_files.rs b/crates/ui-egui/src/dialogs/javascript_files.rs index 01e3012abe..ba188deb19 100644 --- a/crates/ui-egui/src/dialogs/javascript_files.rs +++ b/crates/ui-egui/src/dialogs/javascript_files.rs @@ -16,7 +16,7 @@ use craft::behavior::{Selection, keyed}; use craft::host::PickRequest; use craft::ui::buttons::Button; -use craft::ui::contract::{Bind, CollectionEvent, Props as _, Show as _, ShowCollection as _, ShowContainer as _, Sizing, clicked}; +use craft::ui::contract::{Bind, Props as _, SelectMode, Show as _, ShowCollection as _, ShowContainer as _, Sizing, clicked}; use craft::ui::dialog::{Dialog, DialogId, DialogResult, DialogStack, StackDialog, dialog_id}; use craft::ui::form::Field; use craft::ui::layout_components::Row; @@ -199,22 +199,21 @@ const LIST_ROWS: u16 = 6; fn body(ui: &mut Ui, files: &[(String, String)], form: &mut Form) { let source = keyed(files, |(linked, _): &(String, String)| linked.clone()); - let selection = - selected_row(files, &form.selected).and_then(|i| files.get(i)).map(|(linked, _)| Selection::single(linked.clone())).unwrap_or_default(); - let list = List::::options(tl!("Linked files")) + let selected = selected_row(files, &form.selected).map(|i| &files[i].0); + let mut selection = selected.map(|linked| Selection::single(linked.clone())).unwrap_or_default(); + List::new(tl!("Linked files")) + .select(SelectMode::Single) .min_rows(LIST_ROWS) .max_rows(LIST_ROWS) - .selection(Bind::given(selection)) + .selection(Bind::bound(&mut selection)) .sizing(Sizing::FillWidth) .empty(tl!("No JavaScript files linked")) .show_items(ui, &source, &mut |key, _| { // Paths and URLs are data: shown as they are. ListRow::new(files.iter().find(|(linked, _)| linked == key).map_or_else(String::new, |(_, shown)| shown.clone())) }); - for event in list.events { - if let CollectionEvent::Activate(key) = event { - form.selected = key; - } + if selection.items.first() != selected { + form.selected = selection.items.into_iter().next().unwrap_or_default(); } Field::new(caption("File or URL:")).show(ui, |ui, _| { let request = PickRequest::open("javascript").filter("JavaScript", &["js"]); @@ -243,6 +242,7 @@ mod tests { use craft::host::{AppInfo, Host, Picked, ScriptedFiles}; use craft::ui::testing::Fixture; + use egui::{Key, Modifiers}; use vectorcraft_engine::Session; use super::*; @@ -288,6 +288,26 @@ mod tests { assert_eq!(json_selected(&panel), json!("https://example.com/b.js")); } + #[test] + fn arrow_navigation_changes_which_javascript_file_remove_unlinks() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 100, "height": 100})).unwrap(); + for file in ["scripts/first.js", "scripts/second.js"] { + app.run("svgInteractivity.addFile", json!({"file": file})).unwrap(); + } + let mut panel = Panel::new(app, draw); + panel.app().run("ui.javascriptFilesDialog", json!({})).unwrap(); + panel.frame(); + panel.frame(); + + panel.click("scripts/first.js"); + assert_eq!(json_selected(&panel), "scripts/first.js"); + panel.key(Key::ArrowDown, Modifiers::NONE); + assert_eq!(json_selected(&panel), "scripts/second.js"); + panel.click(tl!("Remove")); + assert_eq!(panel.app().session.active().unwrap().doc.svg_scripts, ["scripts/first.js"]); + } + /// In a frame drawn with read roots in force, the list names a linked file outside them by its /// file name alone, and that name unlinks it; the person sees the whole path. #[test] From 4b5d4464f2a49e09e55bbeb092417c7ec1cf7d13 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 26 Nov 2026 09:01:24 -0800 Subject: [PATCH 110/151] Keep Layers selection-square drags in their source document --- crates/ui-egui/src/panels/layers/cells.rs | 27 ++++++++------- crates/ui-egui/src/panels/layers/rows.rs | 4 +-- crates/ui-egui/src/panels/layers/tests.rs | 40 +++++++++++++++++++++++ 3 files changed, 57 insertions(+), 14 deletions(-) diff --git a/crates/ui-egui/src/panels/layers/cells.rs b/crates/ui-egui/src/panels/layers/cells.rs index 1b9bdadd43..9d2eb797b9 100644 --- a/crates/ui-egui/src/panels/layers/cells.rs +++ b/crates/ui-egui/src/panels/layers/cells.rs @@ -33,10 +33,12 @@ const SQUARE_SIDE: f32 = 7.0; /// The side of the square of a row that holds selected art. const HELD_SIDE: f32 = 4.0; -/// The selected art a row's selection square carries to another row: the selected objects when the -/// drag started. Only the Layers rows take it. +/// The selected art a row's selection square carries to another row in the same document. #[derive(Clone, Debug)] -pub(super) struct ArtDrag(pub(super) Vec); +pub(super) struct ArtDrag { + pub(super) document: u64, + pub(super) ids: Vec, +} /// What a cell reports. #[derive(Clone, Copy, Debug, PartialEq)] @@ -204,6 +206,7 @@ impl Component for TargetCircle { pub(super) struct SelectionSquare { #[common] common: Common, + document: u64, id: Option, selected: bool, holds: bool, @@ -214,13 +217,13 @@ pub(super) struct SelectionSquare { } impl SelectionSquare { - fn new(id: Option, selected: bool, holds: bool, color: DataColor, art: Vec) -> Self { - Self { common: Common::new(), id, selected, holds, color, art, pick: None } + fn new(document: u64, id: Option, selected: bool, holds: bool, color: DataColor, art: Vec) -> Self { + Self { common: Common::new(), document, id, selected, holds, color, art, pick: None } } /// A selected row's square, for the suite. fn sample() -> Self { - Self::new(Some(NodeId(1)), true, false, DataColor::new(Color32::from_rgb(79, 128, 255)), vec![NodeId(1)]).label("Select art") + Self::new(1, Some(NodeId(1)), true, false, DataColor::new(Color32::from_rgb(79, 128, 255)), vec![NodeId(1)]).label("Select art") } } @@ -253,7 +256,7 @@ impl Component for SelectionSquare { self.pick = Some(CellPick::SelectArt(activation.mods)); } if (self.selected || self.holds) && !self.art.is_empty() && primary_drag_start(cx) { - cx.start_drag(ArtDrag(self.art.clone()), DragPreview::None); + cx.start_drag(ArtDrag { document: self.document, ids: self.art.clone() }, DragPreview::None); } } @@ -369,18 +372,18 @@ pub(super) fn build(tree: &DocLayers<'_>, row: &RowId, info: &LayerInfo) -> Cell let selected = |id: NodeId| tree.is_selected(id); match *row { RowId::Node(id) => { - let Some(n) = tree.doc().node(id) else { return Cells::new(None, SelectionSquare::new(None, false, false, color, vec![])) }; + let Some(n) = tree.doc().node(id) else { return Cells::new(None, SelectionSquare::new(st.uid, None, false, false, color, vec![])) }; let is_sel = selected(id); let (full, holds) = square_marks(tree, n); let art = if full || holds { st.selection.objects.clone() } else { vec![] }; let circle = TargetCircle::new(id, shows_targeted(tree, n, is_sel), has_styled_target(n)) .label(crate::i18n::fmt(tl!("Target {row}"), &[("row", info.name.as_str())])); - let square = SelectionSquare::new(Some(id), full, holds, color, art) + let square = SelectionSquare::new(st.uid, Some(id), full, holds, color, art) .label(crate::i18n::fmt(tl!("Select art of {row}"), &[("row", info.name.as_str())])); Cells::new(Some(circle), square) } - RowId::Guide(i) => Cells::new(None, SelectionSquare::new(None, tree.guides().contains(&i), false, color, vec![])), - RowId::Spine(blend) => Cells::new(None, SelectionSquare::new(None, selected(blend), false, color, vec![])), + RowId::Guide(i) => Cells::new(None, SelectionSquare::new(st.uid, None, tree.guides().contains(&i), false, color, vec![])), + RowId::Spine(blend) => Cells::new(None, SelectionSquare::new(st.uid, None, selected(blend), false, color, vec![])), } } @@ -410,6 +413,6 @@ pub(super) fn output( /// layer or group that takes the objects ([`DocLayers::lands_in`]). pub(super) fn accepts_art<'a>(tree: &'a DocLayers<'a>) -> impl Fn(&ArtDrag, &RowId, LayerPosition) -> bool + 'a { move |art: &ArtDrag, row: &RowId, position: LayerPosition| { - position == LayerPosition::Into && matches!(*row, RowId::Node(id) if tree.lands_in(id, &art.0, true)) + art.document == tree.state().uid && position == LayerPosition::Into && matches!(*row, RowId::Node(id) if tree.lands_in(id, &art.ids, true)) } } diff --git a/crates/ui-egui/src/panels/layers/rows.rs b/crates/ui-egui/src/panels/layers/rows.rs index 6cf12c1a95..523e9653ed 100644 --- a/crates/ui-egui/src/panels/layers/rows.rs +++ b/crates/ui-egui/src/panels/layers/rows.rs @@ -463,8 +463,8 @@ fn drop_command(tree: &DocLayers<'_>, mv: &LayerMove) -> Option<(String, /// The selected art carried by a row's selection square, dropped on `target`: the selection's top /// objects, as Arrange and Group take them, move there (Alt copies them). fn art_drop(st: &DocState, payload: &DropPayload, target: NodeId, position: LayerPosition, copy: bool) -> Option<(String, Value)> { - let art = payload.get::()?; - let ids: Vec = st.doc.paint_order(art.0.iter().copied()).iter().map(|i| i.0).collect(); + let art = payload.get::().filter(|art| art.document == st.uid)?; + let ids: Vec = st.doc.paint_order(art.ids.iter().copied()).iter().map(|i| i.0).collect(); Some(("layer.move".into(), json!({"ids": ids, "target": target.0, "place": place(position), "copy": copy}))) } diff --git a/crates/ui-egui/src/panels/layers/tests.rs b/crates/ui-egui/src/panels/layers/tests.rs index a8db112a6a..9b06388014 100644 --- a/crates/ui-egui/src/panels/layers/tests.rs +++ b/crates/ui-egui/src/panels/layers/tests.rs @@ -524,6 +524,46 @@ fn name_row(app: &mut VectorcraftApp, id: NodeId, name: &str) { app.session.execute("layer.setProps", &json!({"ids": [id.0], "name": name})).unwrap(); } +#[test] +fn a_selection_square_drop_after_next_document_leaves_the_new_artwork_in_place() { + use crate::tests::panel_harness::Panel; + use craft::ui::contract::Role; + use craft::ui::runtime::drag; + use egui::{Key, Modifiers}; + + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + let mut setup = |x| { + app.run("file.new", json!({"width": 200, "height": 200})).unwrap(); + let source = app.session.active().unwrap().doc.layers[0].id; + name_row(&mut app, source, "Source"); + let id = app.run("shape.rectangle", json!({"x": x, "y": 20, "width": 40, "height": 30})).unwrap()["id"].as_u64().unwrap(); + let dst = app.run("layer.new", json!({"name": "Destination"})).unwrap()["id"].as_u64().unwrap(); + app.run("select.set", json!({"ids": [id]})).unwrap(); + (app.session.active().unwrap().uid, NodeId(id), source, NodeId(dst)) + }; + let (first_doc, first, _, _) = setup(10); + let (second_doc, second, source, destination) = setup(60); + assert_eq!(first, second, "the documents have different rectangles with the same local ID"); + assert!(app.session.set_active(0)); + + let mut panel = Panel::new(app, show); + let from = panel.rect_role("Select art of Source", Role::BUTTON).center(); + let to = panel.rect("Destination").center(); + panel.drag_hold_role("Select art of Source", Role::BUTTON, to - from); + assert!(drag::mark(panel.ctx()).is_some(), "the destination accepts artwork in its own document"); + panel.key(Key::F6, Modifiers::COMMAND); + assert_eq!(panel.app().session.active().unwrap().uid, second_doc); + let carried = drag::active::(panel.ctx()).expect("the shortcut leaves the drag held"); + assert_eq!((carried.document, carried.ids.as_slice()), (first_doc, &[first][..])); + assert!(drag::mark(panel.ctx()).is_none(), "the destination rejects the foreign artwork"); + panel.release(); + let layer = |app: &VectorcraftApp| app.session.active().unwrap().doc.layer_of(second); + assert_eq!(layer(&panel.app()), Some(source), "the same-ID rectangle in this document has not moved"); + + panel.drag("Select art of Source", "Destination", Modifiers::NONE); + assert_eq!(layer(&panel.app()), Some(destination), "a same-document selection-square drag still moves the rectangle"); +} + /// The target and the selected objects, sorted. fn targeted(app: &VectorcraftApp) -> (Option, Vec) { let st = app.session.active().unwrap(); From 2422350fc1f9d4d44192a1d5c1f32173a2064b15 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 26 Nov 2026 09:05:01 -0800 Subject: [PATCH 111/151] Keep Layers row footer drops in the source document --- crates/ui-egui/src/panels/layers/controls.rs | 33 +++++++------- crates/ui-egui/src/panels/layers/tests.rs | 46 ++++++++++++++++++++ 2 files changed, 62 insertions(+), 17 deletions(-) diff --git a/crates/ui-egui/src/panels/layers/controls.rs b/crates/ui-egui/src/panels/layers/controls.rs index b337508c90..17c66bfe68 100644 --- a/crates/ui-egui/src/panels/layers/controls.rs +++ b/crates/ui-egui/src/panels/layers/controls.rs @@ -1,8 +1,8 @@ use craft::behavior::IconId; use craft::keymap::Mods; -use craft::layers::ui::panel::MenuTarget; // PLAN: assumed path of craft-layers' panel types +use craft::layers::ui::panel::{LayersDrag, MenuTarget, document_hash}; use craft::layers::ui::tree::LayerRowKey; -use craft::ui::contract::{Entry, ListDrag, Show as _}; +use craft::ui::contract::{Entry, Show as _}; use craft::ui::display::{Elide, Text}; use craft::ui::menu::{MenuRow, PanelRow}; use craft::ui::primitives::IconSpec; @@ -347,19 +347,18 @@ fn spine_menu(tree: &DocLayers, blend: NodeId) -> Vec> { /// What was dropped on a footer action. pub(super) enum FooterPayload<'a> { /// Rows of the panel. - Rows(&'a [LayerRowKey]), + Rows(&'a [&'a RowId]), /// The target circle of an appearance (its node id). Appearance(u64), } /// The node ids and the ruler guide indexes among `keys`. -fn row_ids(keys: &[LayerRowKey]) -> (Vec, Vec) { +fn row_ids(keys: &[&RowId]) -> (Vec, Vec) { let (mut nodes, mut guides) = (vec![], vec![]); for key in keys { match key { - LayerRowKey::Layer(RowId::Node(id) | RowId::Spine(id)) => nodes.push(id.0), - LayerRowKey::Layer(RowId::Guide(i)) => guides.push(*i), - _ => {} + RowId::Node(id) | RowId::Spine(id) => nodes.push(id.0), + RowId::Guide(i) => guides.push(*i), } } (nodes, guides) @@ -433,19 +432,19 @@ pub(crate) fn footer(tree: &DocLayers, ui: &mut Ui, out: &mut Vec<(String, Value let locate_ok = !layers_only || super::rows::locate_layer_listed(tree.doc(), tree.root()); let root = tree.root(); let icon = |name: &'static str| IconSpec::svg(IconId::new(name)); - let layer_rows = |keys: &[LayerRowKey]| keys.iter().all(|key| matches!(key, LayerRowKey::Layer(_))); + let document = document_hash(st.uid); + let own = move |drag: &LayersDrag| drag.document() == Some(document); + let duplicate = move |drag: &LayersDrag| { + let (nodes, guides) = row_ids(&drag.layers()); + own(drag) && !nodes.is_empty() && guides.is_empty() && !root.is_some_and(|r| nodes.contains(&r.0)) + }; let actions = [ // PLAN: the framework's `accepts_drops` takes one payload type, so Delete cannot also take // `PanelDrag` (the appearance drop `footer_drop` maps); it needs a second payload there. FooterAction::new(icon("trash-2"), tl!("Delete Selection").to_string()) .takes_drops_disabled(true) - .accepts_drops(move |d: &ListDrag>| layer_rows(&d.keys)), - FooterAction::new(icon("file-plus"), tl!("Create New Layer").to_string()).enabled(new_layer_ok).accepts_drops( - move |d: &ListDrag>| { - let (nodes, guides) = row_ids(&d.keys); - layer_rows(&d.keys) && guides.is_empty() && !root.is_some_and(|r| nodes.contains(&r.0)) - }, - ), + .accepts_drops(move |d: &LayersDrag| own(d) && !d.layers().is_empty()), + FooterAction::new(icon("file-plus"), tl!("Create New Layer").to_string()).enabled(new_layer_ok).accepts_drops(duplicate), FooterAction::new(icon("plus"), tl!("Create New Sublayer").to_string()).enabled(new_sublayer_ok), FooterAction::new(icon("frame"), tl!("Make/Release Clipping Mask").to_string()), FooterAction::new(icon("search"), if layers_only { tl!("Locate Layer").to_string() } else { tl!("Locate Object").to_string() }) @@ -462,8 +461,8 @@ pub(crate) fn footer(tree: &DocLayers, ui: &mut Ui, out: &mut Vec<(String, Value } out.extend(output.picked.and_then(|index| footer_pick(tree, index, output.mods))); if let Some(drop) = &output.dropped { - let run = if let Some(d) = drop.payload::>>() { - footer_drop(tree, drop.index, FooterPayload::Rows(&d.keys)) + let run = if let Some(d) = drop.payload::>().filter(|d| own(d)) { + footer_drop(tree, drop.index, FooterPayload::Rows(&d.layers())) } else if let Some(PanelDrag::Appearance(id)) = drop.payload::() { footer_drop(tree, drop.index, FooterPayload::Appearance(id.0)) } else { diff --git a/crates/ui-egui/src/panels/layers/tests.rs b/crates/ui-egui/src/panels/layers/tests.rs index a8db112a6a..0f56c1b44d 100644 --- a/crates/ui-egui/src/panels/layers/tests.rs +++ b/crates/ui-egui/src/panels/layers/tests.rs @@ -507,6 +507,52 @@ fn context_menu_others_actions_sublayer_state_enables_all_commands() { assert!(lock_enabled, "locked sublayer enables Unlock All Layers"); } +#[test] +fn layer_row_footer_drops_after_next_document_leave_the_new_document_alone() { + use crate::tests::panel_harness::Panel; + use craft::layers::ui::panel::{LayersDrag, document_hash}; + use craft::ui::contract::Role; + use craft::ui::runtime::drag; + use egui::{Key, Modifiers}; + + for (button, deletes) in [("Delete Selection", true), ("Create New Layer", false)] { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + let mut setup = |x| { + app.run("file.new", json!({"width": 200, "height": 200})).unwrap(); + let source = app.session.active().unwrap().doc.layers[0].id; + name_row(&mut app, source, "Dragged Layer"); + app.run("shape.rectangle", json!({"x": x, "y": 20, "width": 40, "height": 30})).unwrap(); + app.run("layer.new", json!({"name": "Other Layer"})).unwrap(); + (app.session.active().unwrap().uid, source) + }; + let (first_doc, first_layer) = setup(10); + let (second_doc, second_layer) = setup(60); + assert_eq!(first_layer, second_layer, "the documents have different layers with the same local ID"); + assert!(app.session.set_active(0)); + + let mut panel = Panel::new(app, show); + let from = panel.rect_role("Dragged Layer", Role::TREE_ITEM).center(); + let to = panel.rect(button).center(); + panel.drag_hold_role("Dragged Layer", Role::TREE_ITEM, to - from); + assert!(drag::mark(panel.ctx()).is_some(), "{button} accepts a drag from its own list"); + panel.key(Key::F6, Modifiers::COMMAND); + assert_eq!(panel.app().session.active().unwrap().uid, second_doc); + let carried = drag::active::>(panel.ctx()).expect("the shortcut leaves the drag held"); + assert_eq!(carried.document(), Some(document_hash(first_doc))); + assert!(drag::mark(panel.ctx()).is_none(), "{button} rejects a drag belonging to another document"); + panel.release(); + assert_eq!(panel.app().session.active().unwrap().doc.layers.len(), 2); + assert!(crate::dialogs::confirm::open_question(&panel.app()).is_none()); + + panel.drag("Dragged Layer", button, Modifiers::NONE); + if deletes { + assert!(crate::dialogs::confirm::open_question(&panel.app()).is_some(), "a same-document drop still asks to delete its layer"); + } else { + assert_eq!(panel.app().session.active().unwrap().doc.layers.len(), 3, "a same-document drop still duplicates its layer"); + } + } +} + /// The footer's layer count is in the accessibility tree, and it follows the document's layers. #[test] fn the_footer_counts_the_layers() { From afd638e75c5ba0ea5335a7ee3f710e33f92c4c6a Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 26 Nov 2026 09:03:51 -0800 Subject: [PATCH 112/151] Restore Enter to apply SVG event scripts --- .../ui-egui/src/panels/svg_interactivity.rs | 27 ++++++++++++++++++- 1 file changed, 26 insertions(+), 1 deletion(-) diff --git a/crates/ui-egui/src/panels/svg_interactivity.rs b/crates/ui-egui/src/panels/svg_interactivity.rs index e444ba1eba..117ae3e0f7 100644 --- a/crates/ui-egui/src/panels/svg_interactivity.rs +++ b/crates/ui-egui/src/panels/svg_interactivity.rs @@ -14,6 +14,7 @@ use craft::ui::form::Field; use craft::ui::list::{List, ListRow}; use craft::ui::menu::PanelRow; use craft::ui::pickers::Select; +use craft::ui::primitives::SubmitKey; use craft::ui::runtime::commands::{CommandState, CommandStates}; use craft::ui::sections::{FooterAction, FooterBar}; use craft::ui::text::TextField; @@ -101,7 +102,13 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { let shown = script.unwrap_or_default(); let mut typed = None; Field::new(caption("JavaScript:")).show(ui, |ui, _| { - let out = TextField::new(caption("JavaScript:"), Bind::given(shown.to_string())).lines(3).id_salt(event).enabled(info.has).show(ui); + let out = TextField::new(caption("JavaScript:"), Bind::given(shown.to_string())) + .lines(3) + .submits() + .submit_key(SubmitKey::Enter) + .id_salt(event) + .enabled(info.has) + .show(ui); typed = out.events.committed().filter(|js| js.as_str() != shown).cloned(); }); let source = keyed(events, |(e, _): &(String, String)| e.clone()); @@ -180,6 +187,24 @@ mod tests { app.session.execute(id, &p).unwrap() } + #[test] + fn enter_applies_the_event_script_and_shift_enter_adds_a_line() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + run(&mut app, "file.new", json!({"width": 100, "height": 100})); + run(&mut app, "shape.rectangle", json!({"x": 0, "y": 0, "width": 50, "height": 50})); + let mut panel = Panel::new(app, show); + + panel.click_role(caption("JavaScript:"), craft::ui::contract::Role::TEXT_INPUT); + panel.type_text("1;"); + panel.key(egui::Key::Enter, egui::Modifiers::SHIFT); + panel.type_text("2;"); + let events = |app: &mut VectorcraftApp| run(app, "svgInteractivity.info", json!({}))["events"].clone(); + assert_eq!(events(&mut panel.app()), json!([]), "the script is still a draft"); + + panel.key(egui::Key::Enter, egui::Modifiers::NONE); + assert_eq!(events(&mut panel.app()), json!([{"event": SVG_EVENTS[0], "script": "1;\n2;"}])); + } + // (Only names and scripts are checked: they are shown as they are, while tests running // alongside change the language the labels are drawn in.) #[test] From ea10edaf9bee2d3a0b8ffdb21732ce7a639ffd4c Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 26 Nov 2026 09:10:14 -0800 Subject: [PATCH 113/151] Keep graphic style canvas drops in their source document --- crates/ui-egui/src/canvas/drops.rs | 13 +++---- crates/ui-egui/src/canvas/drops/tests.rs | 39 +++++++++++++++++++-- crates/ui-egui/src/panels/graphic_styles.rs | 26 ++++++++++++++ 3 files changed, 69 insertions(+), 9 deletions(-) diff --git a/crates/ui-egui/src/canvas/drops.rs b/crates/ui-egui/src/canvas/drops.rs index 274b1fde7f..df8e09eb26 100644 --- a/crates/ui-egui/src/canvas/drops.rs +++ b/crates/ui-egui/src/canvas/drops.rs @@ -23,7 +23,7 @@ use crate::doc_windows::Win; use crate::panel_drag::PanelDrag; use crate::panels::brushes::BrushKey; use crate::panels::brushes::BrushLibraries; -use crate::panels::graphic_styles::StyleKey; +use crate::panels::graphic_styles::StyleDrag; use crate::panels::library_panel::{self, LibraryKey, LibraryKind as _}; use crate::panels::symbols::{SymbolKey, SymbolLibraries}; use crate::place::{CanvasDrop, CanvasFiles}; @@ -50,7 +50,7 @@ pub(crate) struct CarriedArt { #[derive(Clone, Debug)] enum Payload { Panel(PanelDrag), - Style(StyleKey), + Style(StyleDrag), Symbol(SymbolKey), Brush(BrushKey), Library(LibraryKey), @@ -171,12 +171,12 @@ impl Component for CanvasDrops<'_> { if self.kind == BodyKind::Live { // The art of this canvas's own document is not accepted as a panel payload: its move resumes. let panel = Target::new(rect, view, covered, |p: &PanelDrag| (!matches!(p, PanelDrag::Art { .. })).then(|| Payload::Panel(p.clone()))); - let style = Target::new(rect, view, covered, |d: &ListDrag| Some(Payload::Style(d.grabbed.clone()))); + let style = Target::new(rect, view, covered, |d: &StyleDrag| (d.document == self.document).then(|| Payload::Style(d.clone()))); let symbol = Target::new(rect, view, covered, |d: &ListDrag| Some(Payload::Symbol(d.grabbed.clone()))); let brush = Target::new(rect, view, covered, |d: &ListDrag| Some(Payload::Brush(d.grabbed.clone()))); let library = Target::new(rect, view, covered, |d: &ListDrag| Some(Payload::Library(d.grabbed.clone()))); let panel = cx.drop_target::(&panel); - let style = cx.drop_target::, _>(&style); + let style = cx.drop_target::(&style); let symbol = cx.drop_target::, _>(&symbol); let brush = cx.drop_target::, _>(&brush); let library = cx.drop_target::, _>(&library); @@ -344,11 +344,12 @@ pub(crate) fn apply_drop(app: &mut VectorcraftApp, drop: &Dropped) -> Result<(), run(app, "brush.apply", json!({"name": key.name, "ids": [owner]})) } }, - Payload::Style(key) => { + Payload::Style(style) if app.session.active().is_some_and(|st| st.uid == style.document) => { let Some(hit) = hit() else { return Ok(()) }; let top = top_object(app, &hit)?; - run(app, "graphicStyle.apply", json!({"name": key, "ids": [top], "add": drop.op == DropOperation::Copy})) + run(app, "graphicStyle.apply", json!({"name": style.name, "ids": [top], "add": drop.op == DropOperation::Copy})) } + Payload::Style(_) => Ok(()), Payload::Panel(PanelDrag::Paint { params, paint, .. }) if !params.is_null() => { if let Some(color) = paint.color() && crate::panels::proxy_cmd(app, false) == "paint.setFill" diff --git a/crates/ui-egui/src/canvas/drops/tests.rs b/crates/ui-egui/src/canvas/drops/tests.rs index a9a8833daa..3261f54128 100644 --- a/crates/ui-egui/src/canvas/drops/tests.rs +++ b/crates/ui-egui/src/canvas/drops/tests.rs @@ -12,6 +12,7 @@ use vectorcraft_geom::Point; use super::{CarriedArt, Dropped, Payload, apply_drop}; use crate::panel_drag::PanelDrag; use crate::panels::brushes::{BrushKey, BrushLibraries}; +use crate::panels::graphic_styles::StyleDrag; use crate::panels::library_panel::{self, LibraryKey, LibraryKind as _}; use crate::panels::symbols::{SymbolKey, SymbolLibraries}; use crate::{VectorcraftApp, canvas}; @@ -45,6 +46,36 @@ fn undo_len(app: &VectorcraftApp) -> usize { app.session.active().unwrap().history.undo.len() } +#[test] +fn a_foreign_graphic_style_drop_does_not_apply_a_style_with_the_same_name() { + let (mut app, ctx) = app_with_canvas(); + let add = |app: &mut VectorcraftApp, x| { + NodeId(app.run("shape.rectangle", json!({"x": x, "y": 20, "width": 100, "height": 100})).unwrap()["id"].as_u64().unwrap()) + }; + add(&mut app, 20); + app.run("paint.setFill", json!({"color": "#00ff00"})).unwrap(); + app.run("graphicStyle.new", json!({"name": "Shared name"})).unwrap(); + let document = app.session.active().unwrap().uid; + app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); + add(&mut app, 20); + app.run("paint.setFill", json!({"color": "#ed1c24"})).unwrap(); + app.run("graphicStyle.new", json!({"name": "Shared name"})).unwrap(); + let target = add(&mut app, 200); + app.run("paint.setFill", json!({"color": "#0000ff"})).unwrap(); + frame(&mut app, &ctx, vec![]); + + let fill = |app: &VectorcraftApp| app.session.active().unwrap().doc.node(target).unwrap().appearance.fill_paint(); + let before = fill(&app); + let history = undo_len(&app); + let at = Point::new(250.0, 70.0); + let payload = Payload::Style(StyleDrag { document, name: "Shared name".into() }); + for operation in [DropOperation::Move, DropOperation::Copy] { + drop_at(&mut app, payload.clone(), at, operation).unwrap(); + assert_eq!(fill(&app), before); + assert_eq!(undo_len(&app), history, "neither kind of foreign drop makes an edit"); + } +} + /// Each payload's effect, on art and off it: a style applies to the object hit (Alt adds on top), a paint fills it /// and leaves the selection (a gradient fits it), an appearance copies unless dropped on its source, a brush strokes /// the path hit and off art places its art if it has any, a library brush is added and applied in one step, a symbol @@ -67,12 +98,14 @@ fn a_drop_runs_the_effect_of_its_payload() { drop_at(&mut app, Payload::Panel(swatch), on_b, Move).unwrap(); assert_eq!(app.session.active().unwrap().doc.node(b).unwrap().appearance.fill_paint(), red); assert_eq!(app.session.active().unwrap().selection.objects, [a], "the selection stays"); - let name = app.session.active().unwrap().doc.graphic_styles[2].name.clone(); - drop_at(&mut app, Payload::Style(name.clone()), on_b, Move).unwrap(); + let st = app.session.active().unwrap(); + let name = st.doc.graphic_styles[2].name.clone(); + let style = Payload::Style(StyleDrag { document: st.uid, name: name.clone() }); + drop_at(&mut app, style.clone(), on_b, Move).unwrap(); let st = app.session.active().unwrap(); assert_eq!(st.doc.node(b).unwrap().extras().graphic_style, st.doc.graphic_style(&name).map(|g| g.id)); let items = st.doc.node(b).unwrap().appearance.items.len(); - drop_at(&mut app, Payload::Style(name.clone()), on_b, Copy).unwrap(); + drop_at(&mut app, style, on_b, Copy).unwrap(); let added = app.session.active().unwrap().doc.node(b).unwrap(); assert!(added.appearance.items.len() > items && added.extras().graphic_style.is_none(), "with Alt the style goes on top, unlinked"); let fill = |app: &VectorcraftApp| app.session.active().unwrap().doc.node(b).unwrap().appearance.fill_paint(); diff --git a/crates/ui-egui/src/panels/graphic_styles.rs b/crates/ui-egui/src/panels/graphic_styles.rs index a1f3dabb97..4f4d5f8c8f 100644 --- a/crates/ui-egui/src/panels/graphic_styles.rs +++ b/crates/ui-egui/src/panels/graphic_styles.rs @@ -56,6 +56,13 @@ use crate::panel_drag::PanelDrag; /// A style of the panel: its name, which is unique in a document. pub(crate) type StyleKey = String; +/// A document's graphic style dragged out to the canvas. +#[derive(Clone, Debug)] +pub(crate) struct StyleDrag { + pub(crate) document: u64, + pub(crate) name: StyleKey, +} + /// The panel's views (`ui.panelView {panel: "graphicStyles", view}`). #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize)] #[serde(rename_all = "camelCase")] @@ -516,6 +523,7 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { .selection(Bind::bound(&mut panel.selection)) .view_lock(view.preset_view()) .reorder(PresetReorder::items()) + .drag_payload(move |drag: &ListDrag| Some(StyleDrag { document: uid, name: drag.grabbed.clone() })) .empty(tl!("Select styled art and click New Graphic Style.")) .row_items(items) .tip(|ui, key| large_tip(app, &thumbs, ui, key)) @@ -1090,6 +1098,24 @@ mod tests { app.session.active().unwrap().doc.graphic_styles.iter().map(|g| g.name.clone()).collect() } + #[test] + fn a_dragged_graphic_style_carries_the_source_document_to_the_canvas() { + use craft::ui::runtime::drag; + use craft::ui::testing::Fixture; + + let mut app = app(); + app.run("graphicStyle.new", json!({"name": "Dragged Style"})).unwrap(); + let document = app.session.active().unwrap().uid; + let app = RefCell::new(app); + let mut fixture = Fixture::new(move |ui| show(&mut app.borrow_mut(), ui)); + fixture.room(egui::vec2(300.0, 600.0)).settle(); + let from = fixture.by_label("Dragged Style").unwrap().center(); + fixture.drag_hold_at(from, egui::vec2(0.0, 40.0)); + let carried = drag::active::(fixture.ctx()).expect("the Graphic Styles browser supplies the canvas payload"); + assert_eq!(carried.document, document); + assert_eq!(carried.name, "Dragged Style"); + } + fn doc(app: &VectorcraftApp) -> Document { (*app.session.active().unwrap().doc).clone() } From 740d075092ecd6174f95e7b3586ff8058367c75e Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 26 Nov 2026 09:12:23 -0800 Subject: [PATCH 114/151] Follow a linked file selection changed outside the list --- crates/ui-egui/src/dialogs/javascript_files.rs | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/crates/ui-egui/src/dialogs/javascript_files.rs b/crates/ui-egui/src/dialogs/javascript_files.rs index ba188deb19..0b6180745b 100644 --- a/crates/ui-egui/src/dialogs/javascript_files.rs +++ b/crates/ui-egui/src/dialogs/javascript_files.rs @@ -13,7 +13,7 @@ //! In a frame automation drives with read roots in force, the list names a file outside them by //! its file name alone, as `svgInteractivity.info` does; `selected` keeps the file as linked. -use craft::behavior::{Selection, keyed}; +use craft::behavior::{Revision, Selection, keyed}; use craft::host::PickRequest; use craft::ui::buttons::Button; use craft::ui::contract::{Bind, Props as _, SelectMode, Show as _, ShowCollection as _, ShowContainer as _, Sizing, clicked}; @@ -203,6 +203,7 @@ fn body(ui: &mut Ui, files: &[(String, String)], form: &mut Form) { let mut selection = selected.map(|linked| Selection::single(linked.clone())).unwrap_or_default(); List::new(tl!("Linked files")) .select(SelectMode::Single) + .rows_stamp(Revision::of(&selected).get()) .min_rows(LIST_ROWS) .max_rows(LIST_ROWS) .selection(Bind::bound(&mut selection)) @@ -304,6 +305,11 @@ mod tests { assert_eq!(json_selected(&panel), "scripts/first.js"); panel.key(Key::ArrowDown, Modifiers::NONE); assert_eq!(json_selected(&panel), "scripts/second.js"); + // A selection changed outside the list gives the next arrow its new starting row. + set_field(&panel, "selected", "scripts/first.js"); + panel.frame(); + panel.key(Key::ArrowDown, Modifiers::NONE); + assert_eq!(json_selected(&panel), "scripts/second.js"); panel.click(tl!("Remove")); assert_eq!(panel.app().session.active().unwrap().doc.svg_scripts, ["scripts/first.js"]); } From dde0834cb36d38081cdfc22f7fe965d57452308b Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 26 Nov 2026 09:12:36 -0800 Subject: [PATCH 115/151] test: check pending merge state before waiting for the worker Enable the tools testing feature in its own test dependency so CI shards use the same features as the workspace. --- Cargo.lock | 1 + crates/tools/Cargo.toml | 1 + crates/ui-egui/src/control/tests.rs | 2 +- 3 files changed, 3 insertions(+), 1 deletion(-) diff --git a/Cargo.lock b/Cargo.lock index 0417aba6f0..c8dc719a71 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -8930,6 +8930,7 @@ dependencies = [ "vectorcraft-geom 0.24.1", "vectorcraft-pathops 0.24.1", "vectorcraft-text", + "vectorcraft-tools", ] [[package]] diff --git a/crates/tools/Cargo.toml b/crates/tools/Cargo.toml index a89175b05c..e8b705a54a 100644 --- a/crates/tools/Cargo.toml +++ b/crates/tools/Cargo.toml @@ -24,6 +24,7 @@ serde = { workspace = true } serde_json = { workspace = true } [dev-dependencies] +vectorcraft-tools = { workspace = true, features = ["testing"] } craft-image-codecs = { workspace = true } # The tests lay type out in the bundled fonts (the workspace leaves turning them on to the engine). vectorcraft-text = { workspace = true, features = ["test-fonts", "bundled-fonts"] } diff --git a/crates/ui-egui/src/control/tests.rs b/crates/ui-egui/src/control/tests.rs index f895671b1f..d267ab460e 100644 --- a/crates/ui-egui/src/control/tests.rs +++ b/crates/ui-egui/src/control/tests.rs @@ -936,8 +936,8 @@ fn pointer_reply_waits_for_a_merge_on_another_thread() { let revision = app.session.active().unwrap().revision; let mut merge = vectorcraft_tools::builder::testing::pause_next_merge().unwrap(); let click = send(&mut app, json!([{"kind": "down", "x": 15, "y": 10}, {"kind": "up", "x": 15, "y": 10}])); - merge.wait_started().unwrap(); assert!(click.try_recv().is_err() && app.session.tool_editing(), "the click is not answered before the merge is applied"); + merge.wait_started().unwrap(); // A hover sent meanwhile is answered at once; a click is made after the merge, and its // reply waits until then. let hover = send(&mut app, json!([{"kind": "move", "x": 35, "y": 10}])); From bee028c57391ed74d19ee7d3f256733978344298 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 26 Nov 2026 09:13:52 -0800 Subject: [PATCH 116/151] Use the framework revision type exported for UI --- crates/ui-egui/src/dialogs/javascript_files.rs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/crates/ui-egui/src/dialogs/javascript_files.rs b/crates/ui-egui/src/dialogs/javascript_files.rs index 0b6180745b..d15f561816 100644 --- a/crates/ui-egui/src/dialogs/javascript_files.rs +++ b/crates/ui-egui/src/dialogs/javascript_files.rs @@ -13,7 +13,7 @@ //! In a frame automation drives with read roots in force, the list names a file outside them by //! its file name alone, as `svgInteractivity.info` does; `selected` keeps the file as linked. -use craft::behavior::{Revision, Selection, keyed}; +use craft::behavior::{Selection, keyed}; use craft::host::PickRequest; use craft::ui::buttons::Button; use craft::ui::contract::{Bind, Props as _, SelectMode, Show as _, ShowCollection as _, ShowContainer as _, Sizing, clicked}; @@ -22,6 +22,7 @@ use craft::ui::form::Field; use craft::ui::layout_components::Row; use craft::ui::list::{List, ListRow}; use craft::ui::patterns::form_dialogs::PathRow; +use craft::ui::primitives::Revision; use craft::ui::sections::{DialogRole, FooterButton}; use egui::{Context, Ui}; use serde_json::{Value, json}; From 7d5d4039f6d17551c5d8a9ceb921dd9d79e66cb3 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 26 Nov 2026 09:12:24 -0800 Subject: [PATCH 117/151] Cover SVG event script drafts when switching documents --- .../ui-egui/src/panels/svg_interactivity.rs | 28 +++++++++++++++++++ 1 file changed, 28 insertions(+) diff --git a/crates/ui-egui/src/panels/svg_interactivity.rs b/crates/ui-egui/src/panels/svg_interactivity.rs index 117ae3e0f7..07a3fb3d85 100644 --- a/crates/ui-egui/src/panels/svg_interactivity.rs +++ b/crates/ui-egui/src/panels/svg_interactivity.rs @@ -183,6 +183,34 @@ mod tests { use crate::tests::panel_harness::Panel; use vectorcraft_engine::Session; + #[test] + fn script_draft_does_not_follow_the_editor_to_other_artwork() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + for name in ["First", "Second"] { + app.run("file.new", json!({ "name": name, "width": 100, "height": 100 })).unwrap(); + run(&mut app, "shape.rectangle", json!({ "x": 0, "y": 0, "width": 50, "height": 50 })); + } + let mut panel = Panel::new(app, show); + let field = caption("JavaScript:"); + let doc = panel.app().session.active().unwrap().uid; + panel.click_role(field, craft::ui::contract::Role::TEXT_INPUT); + panel.type_text("1;"); + assert_eq!(panel.value(field).as_deref(), Some("1;")); + + panel.app().run("window.nextDocument", json!({})).unwrap(); + panel.frame(); + assert_ne!(panel.app().session.active().unwrap().uid, doc); + assert_eq!(panel.value(field).as_deref(), Some("")); + assert_eq!(run(&mut panel.app(), "svgInteractivity.info", json!({}))["events"], json!([])); + + panel.click_role(field, craft::ui::contract::Role::TEXT_INPUT); + panel.type_text("2;"); + run(&mut panel.app(), "shape.ellipse", json!({ "x": 0, "y": 0, "width": 10, "height": 20 })); + panel.frame(); + assert_eq!(panel.value(field).as_deref(), Some("")); + assert_eq!(run(&mut panel.app(), "svgInteractivity.info", json!({}))["events"], json!([])); + } + fn run(app: &mut VectorcraftApp, id: &str, p: Value) -> Value { app.session.execute(id, &p).unwrap() } From 784996ad4183ce0500596faaceff02b4617b1885 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 26 Nov 2026 09:18:01 -0800 Subject: [PATCH 118/151] Cover character-style leading entry points and Block limits --- crates/engine/src/cmd/typecmd/block_tests.rs | 29 ++++++++++++-------- docs/target-app-parity.md | 4 +-- 2 files changed, 20 insertions(+), 13 deletions(-) diff --git a/crates/engine/src/cmd/typecmd/block_tests.rs b/crates/engine/src/cmd/typecmd/block_tests.rs index 758e011961..eb4afa3760 100644 --- a/crates/engine/src/cmd/typecmd/block_tests.rs +++ b/crates/engine/src/cmd/typecmd/block_tests.rs @@ -33,17 +33,24 @@ fn undo_len(s: &Session) -> usize { #[test] fn editing_a_character_style_keeps_manual_leading_when_block_has_no_room() { - for manual_leading in [42.0, 12.0] { - let mut s = session(); - let id = area(&mut s, 50.0, 400.0, "Inset"); - s.execute("text.areaOptions", &json!({"inset": 30})).unwrap(); - s.execute("charStyle.new", &json!({"name": "Body", "attrs": {"leading": 30}})).unwrap(); - s.execute("charStyle.apply", &json!({"name": "Body", "id": id})).unwrap(); - s.execute("text.setStyle", &json!({"ids": [id], "leading": manual_leading})).unwrap(); - s.execute("type.dynamicText", &json!({"ids": [id], "on": true})).unwrap(); - assert_eq!(text(&s, id).runs[0].style.leading, Some(manual_leading)); - s.execute("charStyle.edit", &json!({"name": "Body", "to": "Body", "attrs": {"leading": 60}})).unwrap(); - assert_eq!(text(&s, id).runs[0].style.leading, Some(manual_leading)); + for command in ["charStyle.setAttrs", "charStyle.edit"] { + for manual_leading in [42.0, 12.0] { + let mut s = session(); + let id = area(&mut s, 50.0, 400.0, "Inset"); + s.execute("text.areaOptions", &json!({"inset": 30})).unwrap(); + s.execute("charStyle.new", &json!({"name": "Body", "attrs": {"leading": 30}})).unwrap(); + s.execute("charStyle.apply", &json!({"name": "Body", "id": id})).unwrap(); + s.execute("text.setStyle", &json!({"ids": [id], "leading": manual_leading})).unwrap(); + s.execute("type.dynamicText", &json!({"ids": [id], "on": true})).unwrap(); + assert_eq!(text(&s, id).runs[0].style.leading, Some(manual_leading)); + let params = if command == "charStyle.edit" { + json!({"name": "Body", "to": "Body", "attrs": {"leading": 60}}) + } else { + json!({"name": "Body", "attrs": {"leading": 60}}) + }; + s.execute(command, ¶ms).unwrap(); + assert_eq!(text(&s, id).runs[0].style.leading, Some(manual_leading), "{command}: {manual_leading}"); + } } } diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index ecc328d206..8197ad34f0 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1863,7 +1863,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur Type › Type on a Path › Center on Top and Center on Bottom (`type.pathCenter.top`, `type.pathCenter.bottom`, also on the Contextual Task Bar for type on a closed path) slide type on a closed path so the middle of its span lands on the path's topmost or bottommost point as drawn, keep the span's length, and set the first paragraph to Center unless it is Center or Justify Center. This is VectorCraft's own behavior (`crates/geom/src/arc.rs`, `crates/engine/src/tests/pathtype.rs`). Type on a Path Options › Align to Path (option names as in [Create type on a path](https://helpx.adobe.com/illustrator/desktop/design-with-text/edit-format-text/create-type-on-a-path.html)) moves each character by its own font, size and vertical scale: Ascender runs the top of the font's em box along the path (the ideographic em box that its `BASE` table, its typographic or `hhea` box or its ideographs give, else an em box centered on the cap height), Descender runs the bottom of the font's bounding box along it, and Center runs a line at half the height of the top of the font's H above the baseline along it. In vertical type, Ascender and Descender move the characters half an em, and Center leaves them on the path. These distances are VectorCraft's own values (`tests::on_path_align_runs_each_glyph_by_its_own_metrics`, `tests::on_path_align_finds_the_em_box_of_each_kind_of_face`, `tests::on_path_align_in_vertical_type_moves_half_an_em`). Type › Dynamic Text (`type.dynamicText`, also on the Contextual Task Bar for type on a path) sizes type on a path to fill the span between its start and end brackets and fits it again after each edit to the text or a bracket ([Dynamic Text overview](https://helpx.adobe.com/photoshop/desktop/text-typography/work-with-dynamic-text/dynamic-text-overview.html), [start and end points](https://helpx.adobe.com/photoshop/desktop/text-typography/work-with-dynamic-text/reposition-start-and-end-points.html)). VectorCraft's own rules: reshaping or scaling the path fits the text again; one factor scales every size, leading and baseline shift; the first character's size moves in 0.1 pt steps within 0.1 to 1,296 pt; turning it off, threading the type or Release Type on a Path keeps the drawn sizes; SVG, EPS, legacy `.ai` and the editing data write the drawn sizes (`crates/text/src/tests/fit.rs`, `crates/engine/src/tests/dynamic_text.rs`). - Dynamic Text on area type is Block (Type › Dynamic Text, the Contextual Task Bar, Area Type Options › Block, the Properties panel's Dynamic Text checkbox with Word Gap and Line Gap; [Dynamic Text overview](https://helpx.adobe.com/photoshop/desktop/text-typography/work-with-dynamic-text/dynamic-text-overview.html)): each line as typed is set to the frame's width by its font size, again after every edit to the text or the frame. VectorCraft's own rules: lines are not broken again, the first character's size moves in 0.1 pt steps within 0.1 to 1,296 pt, Word Gap (0 to 1,000 %, default 100) is the Desired word spacing and Line Gap (-1,296 to 1,296 pt, default 0) is added to each size for the leading, a leading change (the Character and Properties panels, the Type tool's Alt+arrow leading steps, a character style, Text Tweaker) sets Line Gap to the new leading less the size of the first character changed, Reset Panel keeps Line Gap, the sizes are written into the characters, threaded frames cannot use it, and Convert To Point Type turns it off, keeping the sizes (`crates/engine/src/cmd/typecmd/block_tests.rs`). + Dynamic Text on area type is Block (Type › Dynamic Text, the Contextual Task Bar, Area Type Options › Block, the Properties panel's Dynamic Text checkbox with Word Gap and Line Gap; [Dynamic Text overview](https://helpx.adobe.com/photoshop/desktop/text-typography/work-with-dynamic-text/dynamic-text-overview.html)): each line as typed is set to the frame's width by its font size, again after every edit to the text or the frame. VectorCraft's own rules: lines are not broken again, the first character's size moves in 0.1 pt steps within 0.1 to 1,296 pt, Word Gap (0 to 1,000 %, default 100) is the Desired word spacing and Line Gap (-1,296 to 1,296 pt, default 0) is added to each size for the leading, a leading change (the Character and Properties panels, the Type tool's Alt+arrow leading steps, a character style, Text Tweaker) sets Line Gap to the new leading less the size of the first character changed, limited to -1,296 to 1,296 pt, Reset Panel keeps Line Gap, the sizes are written into the characters, threaded frames cannot use it, and Convert To Point Type turns it off, keeping the sizes (`crates/engine/src/cmd/typecmd/block_tests.rs`). Dynamic Text on point type (Type › Dynamic Text, the Contextual Task Bar; [Adjust formatting and resize text](https://helpx.adobe.com/photoshop/desktop/text-typography/work-with-dynamic-text/adjust-formatting-and-resize-text-with-dynamic-text.html) applies it to existing text) turns it into area type with Block on. VectorCraft's own rules: the frame is as wide as the widest line with its indents, so that line keeps its size and place across the page, and it grows in depth to hold every fitted line (`crates/engine/src/cmd/typecmd/block_tests.rs`). Type › Dynamic Text Presets › Circle, Arch and Bow (`type.dynamicTextPreset`) put point type or type on a path on a circular, upward-curving or downward-curving path with Dynamic Text on, with the text's position against the path (above, center, below) and its direction ([Dynamic Text overview](https://helpx.adobe.com/photoshop/desktop/text-typography/work-with-dynamic-text/dynamic-text-overview.html)). VectorCraft's own rules: the circle is as wide as the text and the text starts at its bottom; Arch and Bow are a 120° arc whose chord is as wide as the text; above, center and below are Align to Path's Descender, Center and Ascender (`crates/engine/src/tests/dynamic_text.rs`). The frames of threaded text share one Optical Margin Alignment setting: turning it on or off in one frame sets it in every frame, threading frames gives the thread its first frame's setting, and frames taken out of a thread keep it. @@ -3043,7 +3043,7 @@ A VectorCraft addition, not a feature of the reference app, so no area score mov ## Type Tools add-on: Text Tweaker (2026-11-03) -A VectorCraft addition, not a feature of the reference app, so no area score moves. Object › Plug-ins › Type Tools › Text Tweaker… gives one character attribute (size, baseline shift, character rotation, horizontal or vertical scale, tracking, leading or stroke weight) to the selected characters letter by letter, from a start value to an end value along a straight ramp, an ease in and out, a bow, a spike or at random with a seed, while the text stays live and editable (#4924). Values are set as the Character panel sets them, in its units and ranges, so scaled type takes the sizes shown; spaces and line breaks are skipped unless asked for, each type object gets its own ramp, the range is the Type tool's selection or all the text of the selected type objects, and the run is one undo step from a dialog with Preview. Tests: `cmd::addons::typetools::tests` in `vectorcraft-engine` (each shape, each attribute, skipped spaces, ranges, one ramp per object, seeded random values, scaled type, one undo step, bad params refused), `addons::typetools::tests` in `vectorcraft-ui-egui` (the submenu, the dialog, Preview and Cancel, OK) and `command_sweep`. Commands: `docs/mcp.md` › Type Tools add-on. +A VectorCraft addition, not a feature of the reference app, so no area score moves. Object › Plug-ins › Type Tools › Text Tweaker… gives one character attribute (size, baseline shift, character rotation, horizontal or vertical scale, tracking, leading or stroke weight) to the selected characters letter by letter, from a start value to an end value along a straight ramp, an ease in and out, a bow, a spike or at random with a seed, while the text stays live and editable (#4924). With Block enabled, a leading ramp sets Line Gap from the first changed character instead of varying leading across the text. Values are set as the Character panel sets them, in its units and ranges, so scaled type takes the sizes shown; spaces and line breaks are skipped unless asked for, each type object gets its own ramp, the range is the Type tool's selection or all the text of the selected type objects, and the run is one undo step from a dialog with Preview. Tests: `cmd::addons::typetools::tests` in `vectorcraft-engine` (each shape, each attribute, skipped spaces, ranges, one ramp per object, seeded random values, scaled type, one undo step, bad params refused), `addons::typetools::tests` in `vectorcraft-ui-egui` (the submenu, the dialog, Preview and Cancel, OK) and `command_sweep`. Commands: `docs/mcp.md` › Type Tools add-on. ## Type Tools add-on: Release Type on a Path (2026-11-05) From 52f5e92f4bbe6bbe67aa30ce965677adb8e0307f Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 26 Nov 2026 09:18:44 -0800 Subject: [PATCH 119/151] Cover Pattern Options drafts when switching documents --- crates/ui-egui/src/panels/pattern_options.rs | 22 ++++++++++++++++++++ 1 file changed, 22 insertions(+) diff --git a/crates/ui-egui/src/panels/pattern_options.rs b/crates/ui-egui/src/panels/pattern_options.rs index 1f3ca8d638..06eb84f622 100644 --- a/crates/ui-egui/src/panels/pattern_options.rs +++ b/crates/ui-egui/src/panels/pattern_options.rs @@ -280,4 +280,26 @@ mod tests { assert!(named(&panel, "Waves"), "Enter applies the name"); assert!(!panel.focused("Name"), "Enter ends the editing"); } + + #[test] + fn a_name_draft_does_not_follow_pattern_options_to_the_next_document() { + let mut panel = editing_panel(); + { + let mut app = panel.app(); + app.run("file.new", json!({"width": 200, "height": 200})).unwrap(); + app.run("shape.rectangle", json!({"x": 0, "y": 0, "width": 10, "height": 10})).unwrap(); + app.run("object.pattern.make", json!({"name": "Dots"})).unwrap(); + } + let source = panel.app().session.active().unwrap().uid; + panel.click_role("Name", craft::ui::contract::Role::TEXT_INPUT); + panel.type_text("Stripes"); + assert_eq!(panel.value("Name").as_deref(), Some("Stripes")); + + panel.app().run("window.nextDocument", json!({})).unwrap(); + panel.frame(); + assert_ne!(panel.app().session.active().unwrap().uid, source); + assert_eq!(panel.value("Name").as_deref(), Some("Dots")); + panel.key(egui::Key::Enter, egui::Modifiers::NONE); + assert!(panel.app().session.active().unwrap().doc.pattern("Dots").is_some()); + } } From 3bbd8b86912df7542964d4cd81a8fa5ff4f8337d Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 26 Nov 2026 09:18:55 -0800 Subject: [PATCH 120/151] Scope Pattern Options to the current pattern edit --- crates/ui-egui/src/panels/pattern_options.rs | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/crates/ui-egui/src/panels/pattern_options.rs b/crates/ui-egui/src/panels/pattern_options.rs index 06eb84f622..d958f72b86 100644 --- a/crates/ui-egui/src/panels/pattern_options.rs +++ b/crates/ui-egui/src/panels/pattern_options.rs @@ -22,7 +22,7 @@ use craft::ui::text::{NumberField, TextField}; use egui::Ui; use serde_json::{Value, json}; use vectorcraft_doc::pattern::{PatternDef, RepeatKind, TileType}; -use vectorcraft_doc::{NodeKind, Unit}; +use vectorcraft_doc::{NodeId, NodeKind}; use super::attributes::side_name; use crate::VectorcraftApp; @@ -41,10 +41,10 @@ pub(crate) struct PatternOptionsPanel { pub(crate) chosen: String, } -fn editing(app: &VectorcraftApp) -> Option<(PatternDef, Unit)> { +fn editing(app: &VectorcraftApp) -> Option<(PatternDef, (u64, NodeId))> { let st = app.session.active()?; let pe = st.doc.pattern_edit.as_ref()?; - Some((st.doc.pattern(&pe.pattern)?.clone(), app.session.general_unit())) + Some((st.doc.pattern(&pe.pattern)?.clone(), (st.uid, pe.layer))) } fn set(app: &mut VectorcraftApp, name: &str, mut p: Value) { @@ -95,7 +95,7 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { .show(ui); return; } - let Some((def, _)) = editing(app) else { + let Some((def, edit_scope)) = editing(app) else { idle(app, ui); return; }; @@ -110,7 +110,8 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { }; let sized = def.size_tile_to_art; let canvas = crate::doc_windows::current(app).map(crate::canvas::canvas_id); - FieldGroup::new(tl!("Pattern Options")).show(ui, |ui, _| { + // The temporary layer identifies this editing session even when the pattern is renamed. + FieldGroup::new(tl!("Pattern Options")).id_salt(edit_scope).show(ui, |ui, _| { // Name commits on Enter or focus loss; Shift+Enter commits too and keeps the focus, so the // renamed pattern's name stays selected for the next edit. Enter ends the editing: the keys go // to the document canvas, as with nothing focused. From 0859e9a6c6e901e6899774002c90f5ba2fdea2be Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 26 Nov 2026 09:19:03 -0800 Subject: [PATCH 121/151] Update Retype font previews while typing --- crates/ui-egui/src/panels/retype.rs | 3 ++- crates/ui-egui/src/panels/retype/tests.rs | 18 ++++++++++++++++++ 2 files changed, 20 insertions(+), 1 deletion(-) diff --git a/crates/ui-egui/src/panels/retype.rs b/crates/ui-egui/src/panels/retype.rs index 77dd92e764..9e90acb631 100644 --- a/crates/ui-egui/src/panels/retype.rs +++ b/crates/ui-egui/src/panels/retype.rs @@ -89,9 +89,10 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { } let typed = TextField::new(tl!("Type your text to preview"), Bind::given(Mixed::Same(app.ui.retype.text.clone()))) .placeholder(tl!("Type your text to preview")) + .keeps_on_escape() .limit(MAX_TEXT) .show(ui); - if let Some(text) = typed.events.committed() { + if let Some(text) = typed.events.value().filter(|text| **text != app.ui.retype.text) { run = Some(("retype.preview", json!({ "text": text }))); } Divider::horizontal().show(ui); diff --git a/crates/ui-egui/src/panels/retype/tests.rs b/crates/ui-egui/src/panels/retype/tests.rs index 41cc0de514..1f4a3f017f 100644 --- a/crates/ui-egui/src/panels/retype/tests.rs +++ b/crates/ui-egui/src/panels/retype/tests.rs @@ -5,6 +5,7 @@ use vectorcraft_engine::Session; use super::{ID, Size, show}; use crate::VectorcraftApp; +use crate::tests::panel_harness::Panel; const SCREEN: egui::Rect = egui::Rect::from_min_max(egui::Pos2::ZERO, egui::pos2(600.0, 900.0)); @@ -138,6 +139,23 @@ fn a_failed_search_leaves_the_list_as_it_was() { assert_eq!(app.run("retype.list", json!({})).unwrap(), listed); } +#[test] +fn typing_updates_the_preview_without_enter_and_escape_keeps_it() { + let mut panel = Panel::new(app(), show); + let label = "Type your text to preview"; + panel.click(label); + assert!(panel.focused(label)); + panel.type_text("Preview"); + assert_eq!(panel.app().run("retype.list", json!({})).unwrap()["text"], "Preview"); + panel.type_text(" sample"); + assert_eq!(panel.app().run("retype.list", json!({})).unwrap()["text"], "Preview sample"); + + panel.key(egui::Key::Escape, egui::Modifiers::NONE); + assert!(!panel.focused(label)); + assert_eq!(panel.value(label).as_deref(), Some("Preview sample")); + assert_eq!(panel.app().run("retype.list", json!({})).unwrap()["text"], "Preview sample"); +} + #[test] fn preview_sets_the_size_and_text_and_reset_keeps_them() { let mut app = app(); From cc4542305ae2161c46416d57e986234b3473dfd8 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 26 Nov 2026 09:15:30 -0800 Subject: [PATCH 122/151] Scope SVG event script drafts to their selected artwork --- .../ui-egui/src/panels/svg_interactivity.rs | 34 ++++++++++++++----- 1 file changed, 25 insertions(+), 9 deletions(-) diff --git a/crates/ui-egui/src/panels/svg_interactivity.rs b/crates/ui-egui/src/panels/svg_interactivity.rs index 07a3fb3d85..2add52ed8e 100644 --- a/crates/ui-egui/src/panels/svg_interactivity.rs +++ b/crates/ui-egui/src/panels/svg_interactivity.rs @@ -42,6 +42,7 @@ pub(crate) struct SvgInteractivityPanel { pub(crate) struct Info { has: bool, events: Option>, + script_target: Option, } /// What [`info`] was read for: (document uid, revision, selection size, first and last selected object). @@ -76,7 +77,12 @@ pub(crate) fn info(app: &mut VectorcraftApp) -> Info { let events = r["events"] .as_array() .map(|a| a.iter().filter_map(|e| Some((e["event"].as_str()?.to_string(), e["script"].as_str()?.to_string()))).collect::>()); - let v = Info { has: r["ids"].as_array().is_some_and(|a| !a.is_empty()), events }; + let mut targets: Vec = r["ids"].as_array().into_iter().flatten().filter_map(Value::as_u64).collect(); + targets.sort_unstable(); + let has = !targets.is_empty(); + // The editor's draft belongs to the actual targets, even if the selection is reordered. + let script_target = has.then(|| egui::IdSalt::new((key.0, targets))); + let v = Info { has, events, script_target }; app.canvas.svg_info = Some((key, v.clone())); v } @@ -106,7 +112,7 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { .lines(3) .submits() .submit_key(SubmitKey::Enter) - .id_salt(event) + .id_salt((event, info.script_target)) .enabled(info.has) .show(ui); typed = out.events.committed().filter(|js| js.as_str() != shown).cloned(); @@ -192,23 +198,33 @@ mod tests { } let mut panel = Panel::new(app, show); let field = caption("JavaScript:"); + let multiline = craft::ui::contract::Role::MULTILINE_TEXT_INPUT; let doc = panel.app().session.active().unwrap().uid; - panel.click_role(field, craft::ui::contract::Role::TEXT_INPUT); + panel.click_role(field, multiline); panel.type_text("1;"); - assert_eq!(panel.value(field).as_deref(), Some("1;")); + assert_eq!(panel.value_role(field, multiline).as_deref(), Some("1;")); panel.app().run("window.nextDocument", json!({})).unwrap(); panel.frame(); assert_ne!(panel.app().session.active().unwrap().uid, doc); - assert_eq!(panel.value(field).as_deref(), Some("")); + assert_eq!(panel.value_role(field, multiline).as_deref(), Some("")); assert_eq!(run(&mut panel.app(), "svgInteractivity.info", json!({}))["events"], json!([])); - panel.click_role(field, craft::ui::contract::Role::TEXT_INPUT); + panel.click_role(field, multiline); panel.type_text("2;"); - run(&mut panel.app(), "shape.ellipse", json!({ "x": 0, "y": 0, "width": 10, "height": 20 })); + let first = panel.app().session.active().unwrap().selection.objects[0].0; + let second = run(&mut panel.app(), "shape.ellipse", json!({ "x": 0, "y": 0, "width": 10, "height": 20 }))["id"].clone(); panel.frame(); - assert_eq!(panel.value(field).as_deref(), Some("")); + assert_eq!(panel.value_role(field, multiline).as_deref(), Some("")); assert_eq!(run(&mut panel.app(), "svgInteractivity.info", json!({}))["events"], json!([])); + + run(&mut panel.app(), "select.set", json!({ "ids": [first, second] })); + panel.frame(); + panel.click_role(field, multiline); + panel.type_text("3;"); + run(&mut panel.app(), "select.set", json!({ "ids": [second, first] })); + panel.frame(); + assert_eq!(panel.value_role(field, multiline).as_deref(), Some("3;")); } fn run(app: &mut VectorcraftApp, id: &str, p: Value) -> Value { @@ -222,7 +238,7 @@ mod tests { run(&mut app, "shape.rectangle", json!({"x": 0, "y": 0, "width": 50, "height": 50})); let mut panel = Panel::new(app, show); - panel.click_role(caption("JavaScript:"), craft::ui::contract::Role::TEXT_INPUT); + panel.click_role(caption("JavaScript:"), craft::ui::contract::Role::MULTILINE_TEXT_INPUT); panel.type_text("1;"); panel.key(egui::Key::Enter, egui::Modifiers::SHIFT); panel.type_text("2;"); From 39b2eda9af919a84f6008c7fadf0fdd3084491a4 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 26 Nov 2026 09:24:15 -0800 Subject: [PATCH 123/151] Start Insert Menu Item keyboard navigation at the filtered selection --- .../src/dialogs/action_insert_menu_item.rs | 70 +++++++++++++++++-- 1 file changed, 66 insertions(+), 4 deletions(-) diff --git a/crates/ui-egui/src/dialogs/action_insert_menu_item.rs b/crates/ui-egui/src/dialogs/action_insert_menu_item.rs index acb6065d7a..9f8ae5af95 100644 --- a/crates/ui-egui/src/dialogs/action_insert_menu_item.rs +++ b/crates/ui-egui/src/dialogs/action_insert_menu_item.rs @@ -19,6 +19,7 @@ use craft::ui::display::{Shade, Text}; use craft::ui::form::{Field, FieldGroup}; use craft::ui::layout_components::Row as Line; use craft::ui::list::{List, ListRow}; +use craft::ui::primitives::Revision; use craft::ui::runtime::env::Label; use craft::ui::text::TextField; use egui::{Context, Ui}; @@ -258,6 +259,7 @@ impl StackDialog for InsertMenuItemDialog { fn show(&mut self, ui: &mut Ui, _: &DialogStack) -> Option> { let rows = &self.rows; + let rows_key = self.key; self.form.show(ui, label("Insert Menu Item"), None, |ui, fields| { FieldGroup::new(label("Insert Menu Item")).show(ui, |ui, _| { let before = fields.find.clone(); @@ -284,16 +286,18 @@ impl StackDialog for InsertMenuItemDialog { } let listed: Vec<&Row> = matches(rows, &fields.find).take(MAX_LISTED).collect(); let texts: Vec = listed.iter().map(|row| row.shown.clone()).collect(); - let lead = listed.iter().position(|row| picked(fields, row)); - let mut selection = lead.map_or_else(Selection::default, Selection::single); + let selected = listed.iter().position(|row| picked(fields, row)); + let mut selection = selected.map_or_else(Selection::default, Selection::single); List::::new(label("Menu Items")) .select(SelectMode::Single) + .rows_stamp(Revision::of(&(rows_key, &fields.find, selected)).get()) .selection(Bind::bound(&mut selection)) .sizing(Sizing::Content) .max_rows(8) .show_items(ui, &Listed(&texts), &mut |key, _| ListRow::new(texts.get(*key).cloned().unwrap_or_default())); - if selection.lead != lead - && let Some(row) = selection.lead.and_then(|at| listed.get(at)) + let chosen = selection.items.first().copied(); + if chosen != selected + && let Some(row) = chosen.and_then(|at| listed.get(at)) { pick(fields, row); } @@ -336,10 +340,13 @@ impl StackDialog for InsertMenuItemDialog { #[cfg(test)] mod tests { + use craft::automation::actions::Action; use craft::menu::Node; + use egui::{Key, Modifiers}; use super::*; use crate::dialogs::actions::pump; + use crate::tests::panel_harness::Panel; fn fields(find: &str, command: &str) -> InsertMenuItemFields { InsertMenuItemFields { find: find.into(), command: command.into(), ..InsertMenuItemFields::default() } @@ -359,6 +366,61 @@ mod tests { assert_eq!((f.note, f.command.as_str()), (FindNote::NoMatch, "object.ungroup"), "a failed Find keeps the pick"); } + #[test] + fn arrow_navigation_inserts_the_command_after_the_selected_filtered_result() { + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + app.run("file.new", json!({"width": 100, "height": 100})).unwrap(); + app.ui.actions = Default::default(); + app.ui.actions.push(Action { set: Some("Test".into()), ..Action::new("View", Vec::new()) }).unwrap(); + let available = build(Lang::EN, true, &menus::Listed::default()); + let fit_params = available.iter().find(|row| row.command == "view.fitArtboard").unwrap().params.clone(); + let rows = [ + ("view.zoomIn", "First command", "first command"), + ("view.zoomOut", "Second command", "remaining commands"), + ("view.fitArtboard", "Third command", "remaining commands"), + ("view.outline", "Fourth command", "remaining commands"), + ] + .into_iter() + .map(|(command, shown, haystack)| Row { + command: command.into(), + params: available.iter().find(|row| row.command == command).unwrap().params.clone(), + shown: shown.into(), + haystack: haystack.into(), + }) + .collect(); + let mut panel = Panel::new(app, |app, ui| app.dialogs().unwrap().with(|host| host.run(ui))); + let dialog = InsertMenuItemDialog { + id: dialog_id(KEY), + target: Target::new(Some((0, 0)), None), + form: Form::new(InsertMenuItemFields::default(), check), + rows, + key: None, + }; + open_or_say(&mut panel.app(), dialog); + panel.frame(); + panel.frame(); + + let dialogs = panel.app().dialogs().unwrap(); + let command = || dialogs.with(|host| host.get::().unwrap().form.values.command.clone()); + panel.click("First command"); + assert_eq!(command(), "view.zoomIn"); + dialogs.with(|host| { + host.set_json_field(panel.ctx(), dialog_id(KEY), "find", json!("remaining")).unwrap(); + host.set_json_field(panel.ctx(), dialog_id(KEY), "command", json!("view.fitArtboard")).unwrap(); + host.set_json_field(panel.ctx(), dialog_id(KEY), "params", fit_params).unwrap(); + }); + panel.frame(); + assert!(!panel.shows("First command")); + panel.key(Key::ArrowDown, Modifiers::NONE); + assert_eq!(command(), "view.outline"); + panel.click(tl!("OK")); + let mut app = panel.app(); + pump(&mut app, panel.ctx()); + let steps = &app.ui.actions.action(0).unwrap().steps; + assert_eq!(steps.len(), 1); + assert_eq!(steps[0].command, "view.outline"); + } + /// The list holds the menu items that run an engine command, and the View menu items that the /// app runs itself, without asking for values first, outside the application, File, Window and /// Help menus, and leaves out Undo, Redo, the Pastes, Image Trace's Make and Make and Expand, From 186a32d171f0a8b79dd642fdef2481015b7fc48d Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 26 Nov 2026 09:39:34 -0800 Subject: [PATCH 124/151] Separations Preview: scroll to Color Settings in short panels --- crates/ui-egui/src/panels/separations.rs | 74 +++++++++++++++++------- 1 file changed, 54 insertions(+), 20 deletions(-) diff --git a/crates/ui-egui/src/panels/separations.rs b/crates/ui-egui/src/panels/separations.rs index 46bed23b0e..1a3e0fefd1 100644 --- a/crates/ui-egui/src/panels/separations.rs +++ b/crates/ui-egui/src/panels/separations.rs @@ -14,8 +14,8 @@ use craft::theme::variant::Tone; use craft::ui::buttons::Button; use craft::ui::choice::{Checkbox, Radio, RadioGroup}; use craft::ui::contract::{ - Bind, CollectionEvent, ColumnSpec, Entry, Lazy, Props as _, SelectMode, Show as _, ShowCollection as _, ShowContainer as _, Sizing, ToggleColumn, - clicked, + Bind, CollectionEvent, ColumnSpec, Entry, Lazy, Props as _, Scroll, SelectMode, Show as _, ShowCollection as _, ShowContainer as _, Sizing, + ToggleColumn, clicked, }; use craft::ui::display::Text; use craft::ui::layout_components::{Row, Stack}; @@ -49,9 +49,6 @@ const EYE: ColumnKey = ColumnKey::new("eye"); const NAME: ColumnKey = ColumnKey::new("name"); /// The command of the panel menu's Show All Plates row. const SHOW_ALL_PLATES: &str = "ui.separations.showAllPlates"; -/// How long the Color Settings section is, for the scroll area before it has been shown once. -const COLOR_SETTINGS_ESTIMATE: f32 = 460.0; - /// Runs command `id` with `p`; a failure goes to the status bar, so it returns `None`. fn act(app: &mut VectorcraftApp, id: &str, p: Value) -> Option { match app.run(id, p) { @@ -421,12 +418,13 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { // The flag is read by every pass of the frame, so a second pass reveals as well; only a real // pass (not a sizing one) spends it. let reveal = app.ui.color_settings_scroll; - Stack::new().label(tl!("Separations Preview")).show(ui, |ui, _| { + Stack::new().label(tl!("Separations Preview")).fill().scroll(Scroll::vertical()).show(ui, |ui, _| { crate::panels::section(tl!("Separations Preview")).show(ui, |ui, _| plates_section(app, ui)); crate::panels::section(tl!("Proof Setup")).show(ui, |ui, _| proof_section(app, ui)); - Lazy::new("color-settings", COLOR_SETTINGS_ESTIMATE).reveal(reveal).show(ui, |ui| { - crate::panels::section(tl!("Color Settings")).show(ui, |ui, _| settings_rows(app, ui)); - }); + // The scroll target is separate from the controls so they are registered for keyboard navigation + // even before the section has scrolled into view. + Lazy::new("color-settings", 0.0).reveal(reveal).show(ui, |_| {}); + crate::panels::section(tl!("Color Settings")).show(ui, |ui, _| settings_rows(app, ui)); }); if reveal && !ui.is_sizing_pass() { app.ui.color_settings_scroll = false; @@ -522,11 +520,6 @@ mod tests { } } - /// The panel inside a vertical scroll area, as the window shows it. - fn scrolled(app: &mut VectorcraftApp, ui: &mut Ui) { - Stack::new().fill().scroll(craft::ui::contract::Scroll::vertical()).show(ui, |ui, _| show(app, ui)); - } - /// #6419: Edit › Assign Profile… and Color Settings… show the panel scrolled to its Color /// Settings section, which a window shorter than the panel (a floated panel stops at 320 /// points) otherwise shows only after scrolling past the plates and Proof Setup. Once: the @@ -534,14 +527,15 @@ mod tests { #[test] fn color_settings_and_assign_profile_scroll_the_color_settings_into_view() { const BPC: &str = "Use Black Point Compensation"; + const HEIGHT: f32 = 200.0; for id in ["edit.assignProfile", "edit.colorSettings"] { let mut app = VectorcraftApp::new(Session::new(), Default::default()); app.run("file.new", json!({})).unwrap(); - let mut panel = Panel::new(app, scrolled); - panel.room(egui::vec2(300.0, 120.0)); + let mut panel = Panel::new(app, show); + panel.room(egui::vec2(300.0, HEIGHT)); panel.frame(); - // The section draws lazily: below the view it is not drawn at all. - assert!(!panel.shows(BPC) || !panel.in_view(BPC), "the section starts below the view"); + // The settings controls start below the view. + assert!(panel.rect(BPC).top() >= HEIGHT, "the section starts below the view"); panel.app().run(id, json!({})).unwrap(); panel.frame(); assert!(!panel.app().ui.color_settings_scroll, "{id}: the pass that read the request spent it"); @@ -549,11 +543,51 @@ mod tests { panel.advance(1.0); panel.frame(); panel.frame(); - assert!(panel.in_view(BPC), "{id} scrolls the section into the view"); + let shown = panel.rect(BPC); + assert!(panel.in_view(BPC) && shown.top() >= 0.0 && shown.bottom() <= HEIGHT, "{id} scrolls the section into the view: {shown:?}"); // PLAN: the harness has no scroll driver, so "a later scroll to the top stays there" is // covered only as far as the spent request not scrolling again. panel.frame(); - assert!(panel.in_view(BPC), "{id}: nothing scrolls it again"); + assert_eq!(panel.rect(BPC), shown, "{id}: nothing scrolls it again"); } } + + #[test] + fn a_short_separations_panel_scrolls_to_the_color_settings_actions() { + use craft::ui::testing::{Fixture, pointer}; + + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({})).unwrap(); + let mut fixture = Fixture::new(move |ui| show(&mut app, ui)); + fixture.room(egui::vec2(220.0, 320.0)).settle(); + let at = |fixture: &Fixture, name| fixture.by_label(name).unwrap().rect; + assert!(at(&fixture, "Load Profile…").top() >= 320.0, "Color Settings starts below the view"); + for _ in 0..6 { + fixture.frame(vec![pointer::moved(egui::pos2(120.0, 250.0)), pointer::wheel(-300.0)]).settle(); + } + for name in ["Load Profile…", "Gamut Check"] { + let rect = at(&fixture, name); + assert!(rect.top() >= 0.0 && rect.bottom() <= 320.0, "{name} scrolls into the view: {rect:?}"); + } + } + + #[test] + fn tab_reaches_color_settings_before_any_manual_scroll() { + use craft::ui::testing::Fixture; + + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({})).unwrap(); + let mut fixture = Fixture::new(move |ui| show(&mut app, ui)); + fixture.room(egui::vec2(300.0, 120.0)).settle(); + let focused_gamut_check = |fixture: &Fixture| fixture.tree().name_of(fixture.tree().focused_key()) == Some("Gamut Check"); + for _ in 0..32 { + fixture.key(egui::Key::Tab, egui::Modifiers::NONE).settle(); + if focused_gamut_check(&fixture) { + break; + } + } + assert!(focused_gamut_check(&fixture)); + let gamut = fixture.by_label("Gamut Check").unwrap().rect; + assert!(gamut.top() >= 0.0 && gamut.bottom() <= 120.0, "focused action scrolls into the view: {gamut:?}"); + } } From 77d511b009f5ca4404a4aa8b0a5acc996ede45d0 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 26 Nov 2026 08:58:58 -0800 Subject: [PATCH 125/151] Make SVG Interactivity events keyboard selectable --- .../ui-egui/src/panels/svg_interactivity.rs | 177 +++++++++++++++--- crates/ui-egui/src/tests/panel_harness.rs | 9 +- 2 files changed, 157 insertions(+), 29 deletions(-) diff --git a/crates/ui-egui/src/panels/svg_interactivity.rs b/crates/ui-egui/src/panels/svg_interactivity.rs index e444ba1eba..6d446a0f22 100644 --- a/crates/ui-egui/src/panels/svg_interactivity.rs +++ b/crates/ui-egui/src/panels/svg_interactivity.rs @@ -6,11 +6,16 @@ //! remove them; Link JavaScript Files… opens the JavaScript Files dialog (`ui.javascriptFilesDialog`). //! Everything reads `svgInteractivity.info`. -use craft::behavior::{IconId, Selection, keyed}; +use std::hash::{DefaultHasher, Hash, Hasher}; + +use craft::behavior::{IconId, Selection, SelectionChange, keyed}; use craft::keymap::CommandRef; -use craft::ui::contract::{Bind, CollectionEvent, Entry, Props as _, Show as _, ShowCollection as _, ShowContainer as _, Sizing}; +use craft::ui::contract::{ + Bind, CollectionEvent, Entry, Politeness, Props as _, SelectMode, Show as _, ShowCollection as _, ShowContainer as _, Sizing, announce, +}; use craft::ui::display::{Shade, Text}; use craft::ui::form::Field; +use craft::ui::layout_components::Stack; use craft::ui::list::{List, ListRow}; use craft::ui::menu::PanelRow; use craft::ui::pickers::Select; @@ -34,6 +39,7 @@ const CLEAR_EVENTS: &str = "svgInteractivity.clearEvents"; pub(crate) struct SvgInteractivityPanel { /// The event picked to edit ([`picked`] reads it). pub(crate) event: String, + list_stamp: u64, } /// The panel's values: whether there are targets, and their events (`None` where they differ). @@ -96,6 +102,8 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { let out = Select::new(caption("Event:"), Bind::given(event.to_string()), &names).enabled(info.has).show(ui); pick = out.events.committed().cloned(); }); + let menu_changed = pick.as_deref().is_some_and(|picked| picked != event); + let reveal = pick.as_ref().filter(|picked| menu_changed && events.iter().any(|(key, _)| key == *picked)).cloned(); // Blank where the objects' events differ; empty where none of them has the event. let script = info.events.as_ref().map(|l| l.iter().find(|(e, _)| e == event).map_or("", |(_, js)| js.as_str())); let shown = script.unwrap_or_default(); @@ -105,45 +113,91 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { typed = out.events.committed().filter(|js| js.as_str() != shown).cloned(); }); let source = keyed(events, |(e, _): &(String, String)| e.clone()); - let selection = if events.iter().any(|(e, _)| e == event) { Selection::single(event.to_string()) } else { Default::default() }; - let list = List::::options(tl!("Events")) - .selection(Bind::given(selection)) - .sizing(Sizing::Fill) - // Event names and scripts are data: shown as they are. - .show_items(ui, &source, &mut |key, _| { - let js = events.iter().find(|(e, _)| e == key).map_or("", |(_, js)| js.as_str()); - ListRow::new(format!("{key}: {js}")) - }); - for e in list.events { - if let CollectionEvent::Activate(key) = e { - pick = Some(key); - } - } - if !info.has && selection_len(app) == 0 { - Text::new(tl!("No Selection")).shade(Shade::Muted).show(ui); + let mut stamp = DefaultHasher::new(); + app.ui.svg_interactivity_panel.list_stamp.hash(&mut stamp); + for (key, _) in events { + key.hash(&mut stamp); } + let rows_stamp = stamp.finish(); + let mut remove = None; + let mut footer_pick = None; let has_doc = app.session.active().is_some(); let listed = events.iter().any(|(e, _)| e == event); - let footer = FooterBar::actions([ - FooterAction::new(IconId::new("trash"), tl!("Remove Selected Entry")).enabled(listed), - FooterAction::new(IconId::new("new_file"), tl!("Link JavaScript Files…")).enabled(has_doc), - ]) - .show_footer(ui); + Stack::new() + .fill() + .footer(|ui, _| { + let footer = FooterBar::actions([ + FooterAction::new(IconId::new("trash"), tl!("Remove Selected Entry")).enabled(listed), + FooterAction::new(IconId::new("new_file"), tl!("Link JavaScript Files…")).enabled(has_doc), + ]) + .show_footer(ui); + if !ui.is_sizing_pass() { + footer_pick = footer.picked; + } + }) + .show(ui, |ui, _| { + if !info.has && selection_len(app) == 0 { + Text::new(tl!("No Selection")).shade(Shade::Muted).show(ui); + return; + } + let selection = if listed { Selection::single(event.to_string()) } else { Default::default() }; + let mut list = List::::new(tl!("Events")) + .select(SelectMode::Single) + .arrows_select(true) + .deletable(true) + .rows_stamp(rows_stamp) + .selection(Bind::given(selection)) + .sizing(Sizing::Fill); + if let Some(key) = reveal.as_ref() { + list = list.reveal(key.clone()); + } + // Event names and scripts are data: shown as they are. + let list = list.show_items(ui, &source, &mut |key, _| { + let js = events.iter().find(|(e, _)| e == key).map_or("", |(_, js)| js.as_str()); + ListRow::new(format!("{key}: {js}")) + }); + if ui.is_sizing_pass() { + return; + } + for e in list.events { + match e { + CollectionEvent::Selection { change: SelectionChange::Set(keys), .. } => { + if let Some(key) = keys.into_iter().next() { + pick = Some(key); + } + } + CollectionEvent::Activate(key) => pick = Some(key), + CollectionEvent::Delete(_) => { + remove = pick.as_deref().or(listed.then_some(event)).map(str::to_owned); + } + _ => {} + } + } + }); if let Some(e) = pick { - app.ui.svg_interactivity_panel.event = e; + let state = &mut app.ui.svg_interactivity_panel; + state.event = e; + if menu_changed { + // The list must seed its keyboard position from the new picker selection. + state.list_stamp = state.list_stamp.wrapping_add(1); + } } if let Some(js) = typed { app.run("svgInteractivity.setEvent", json!({ "event": event, "script": js })).ok(); } - match footer.picked { - Some(0) => { - app.run("svgInteractivity.removeEvent", json!({ "event": event })).ok(); - } + match footer_pick { + Some(0) => remove = Some(event.to_string()), Some(1) => { crate::menus::invoke(app, "ui.javascriptFilesDialog", json!({})); } _ => {} } + if let Some(event) = remove + && app.run("svgInteractivity.removeEvent", json!({ "event": event })).is_ok_and(|out| out["changed"].as_u64().unwrap_or(0) > 0) + { + let message = crate::i18n::fmt(tl!("Removed SVG event {event}"), &[("event", &event)]); + announce(ui.ctx(), message, Politeness::Polite); + } } /// The panel (≡) menu's rows: Clear Events. @@ -215,4 +269,71 @@ mod tests { assert_eq!(panel.value(caption("JavaScript:")).as_deref(), Some("")); assert!(info(&mut panel.app()).events.is_none()); } + + #[test] + fn keyboard_selection_edits_and_removes_the_chosen_event() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + run(&mut app, "file.new", json!({"width": 100, "height": 100})); + run(&mut app, "shape.rectangle", json!({"x": 0, "y": 0, "width": 50, "height": 50})); + run(&mut app, "svgInteractivity.setEvent", json!({"event": "onclick", "script": "1;"})); + run(&mut app, "svgInteractivity.setEvent", json!({"event": "onmouseover", "script": "2;"})); + let mut panel = Panel::new(app, show); + + panel.click("onclick: 1;"); + assert_eq!(panel.value(caption("JavaScript:")).as_deref(), Some("1;")); + panel.key(egui::Key::ArrowDown, egui::Modifiers::NONE); + assert_eq!(panel.value(caption("JavaScript:")).as_deref(), Some("2;")); + + panel.click(caption("Event:")); + panel.click("onclick"); + panel.focus(tl!("Events")); + panel.key(egui::Key::ArrowDown, egui::Modifiers::NONE); + assert_eq!(panel.value(caption("JavaScript:")).as_deref(), Some("2;")); + + panel.key(egui::Key::ArrowUp, egui::Modifiers::SHIFT); + assert_eq!(panel.value(caption("JavaScript:")).as_deref(), Some("2;")); + let delete = + |pressed| egui::Event::Key { key: egui::Key::Delete, physical_key: None, pressed, repeat: false, modifiers: egui::Modifiers::NONE }; + panel.frame_with(vec![delete(true)]); + let removed = crate::i18n::fmt(tl!("Removed SVG event {event}"), &[("event", "onmouseover")]); + assert!(panel.announces(&removed), "the removal is announced"); + panel.frame_with(vec![delete(false)]); + panel.frame(); + assert!(panel.shows("onclick: 1;")); + assert!(!panel.shows("onmouseover: 2;")); + assert_eq!(panel.app().session.active().unwrap().selection.objects.len(), 1); + panel.app().run("edit.undo", json!({})).unwrap(); + panel.frame(); + assert_eq!(panel.value(caption("JavaScript:")).as_deref(), Some("2;")); + panel.key(egui::Key::Delete, egui::Modifiers::NONE); + assert!(!panel.shows("onmouseover: 2;")); + panel.key(egui::Key::Delete, egui::Modifiers::NONE); + assert!(panel.shows("onclick: 1;"), "Delete must leave an unselected event alone"); + panel.key(egui::Key::ArrowDown, egui::Modifiers::NONE); + assert_eq!(panel.value(caption("JavaScript:")).as_deref(), Some("1;")); + panel.click("Remove Selected Entry"); + assert!(!panel.shows("onclick: 1;")); + } + + #[test] + fn picking_an_event_reveals_its_row_in_a_short_panel() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + run(&mut app, "file.new", json!({ "width": 100, "height": 100 })); + run(&mut app, "shape.rectangle", json!({ "x": 0, "y": 0, "width": 50, "height": 50 })); + for (i, event) in SVG_EVENTS.into_iter().enumerate() { + run(&mut app, "svgInteractivity.setEvent", json!({ "event": event, "script": i.to_string() })); + } + let script = (SVG_EVENTS.len() - 1).to_string(); + let last = format!("{}: {script}", SVG_EVENTS.last().unwrap()); + let mut panel = Panel::new(app, show); + panel.room(egui::vec2(300.0, 220.0)); + panel.frame(); + assert!(!panel.shows(&last) || !panel.in_view(&last)); + + panel.click(caption("Event:")); + panel.key(egui::Key::End, egui::Modifiers::NONE); + panel.key(egui::Key::Enter, egui::Modifiers::NONE); + assert_eq!(panel.value(caption("JavaScript:")).as_deref(), Some(script.as_str())); + assert!(panel.in_view(&last), "the picker scrolls the selected event into view"); + } } diff --git a/crates/ui-egui/src/tests/panel_harness.rs b/crates/ui-egui/src/tests/panel_harness.rs index 71977801c5..9065e07011 100644 --- a/crates/ui-egui/src/tests/panel_harness.rs +++ b/crates/ui-egui/src/tests/panel_harness.rs @@ -11,6 +11,7 @@ use std::{ }; use craft::behavior::PartRef; +use craft::ui::contract::Role; use craft::ui::runtime::frame::take_output; use craft::ui::testing::pointer::part_rect_of_node; use craft::ui::testing::{Fixture, Target}; @@ -63,7 +64,7 @@ impl Panel { } /// One frame with `events`, its input taken from the app first. - fn frame_with(&mut self, events: Vec) { + pub(crate) fn frame_with(&mut self, events: Vec) { self.take_input(); self.fixture.frame(events); self.take_input(); @@ -293,6 +294,12 @@ impl Panel { self.fixture.by_label(name).is_some() } + /// Whether the latest frame has a status announcement with this text. + pub(crate) fn announces(&self, text: &str) -> bool { + let tree = self.fixture.tree(); + tree.keys().into_iter().any(|key| tree.role_of(key) == Some(Role::STATUS) && tree.name_of(key) == Some(text)) + } + /// Whether some of the control named `name` can be seen in the latest frame. pub(crate) fn in_view(&self, name: &str) -> bool { self.fixture.visible(&self.look(name)).is_some() From 72984fddaacd6ec248ccb1acaea34ae96d58b20e Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 26 Nov 2026 09:53:08 -0800 Subject: [PATCH 126/151] Enforce data limits on host receivers and indexers --- crates/js/src/host.rs | 63 +++++++++++++++++++++++++---------- crates/js/src/host_classes.rs | 13 +++++--- crates/js/src/host_tests.rs | 48 ++++++++++++++++++++++++++ 3 files changed, 103 insertions(+), 21 deletions(-) diff --git a/crates/js/src/host.rs b/crates/js/src/host.rs index 4e0275441a..276895e782 100644 --- a/crates/js/src/host.rs +++ b/crates/js/src/host.rs @@ -30,6 +30,7 @@ pub enum Data { } /// How much one crossing may carry. +/// Host receivers, their handles and explicit arguments share these limits. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub struct DataLimits { /// How deeply arrays and objects may nest. @@ -265,9 +266,7 @@ impl Interp { return Err(self.data_error(r, ErrorType::Range, "is nested too deep")); } let shape = match &self.object(id)?.class { - Class::Host(_) if r.hosted => { - return self.host_ref_of(id)?.ok_or_else(|| Abrupt::Internal("host object without a class".into())); - } + Class::Host(_) if r.hosted => return self.read_host_ref(id, r), Class::Host(_) => return Err(self.data_error(r, ErrorType::Type, "is an object of a host class, not plain data")), Class::Array { length, .. } => Shape::Array(*length), Class::Ordinary => { @@ -299,6 +298,14 @@ impl Interp { out } + fn read_host_ref(&mut self, id: ObjId, r: &mut Reading) -> JsResult { + let Some((name, len)) = self.host_ref_size(id)? else { return Err(Abrupt::Internal("host object without a class".into())) }; + self.charge_entries(r, len.saturating_add(2))?; + let key = crate::HOST_REF_KEY.len().saturating_mul(3).saturating_add(8); + self.charge_reading(r, key.saturating_add(name.saturating_mul(3)).saturating_add(2))?; + self.host_ref_of(id)?.ok_or_else(|| Abrupt::Internal("host object without a class".into())) + } + fn read_array(&mut self, id: ObjId, length: u32, r: &mut Reading) -> JsResult { self.charge_entries(r, length as usize)?; let mut items = Vec::with_capacity(length as usize); @@ -407,16 +414,8 @@ impl Interp { pub(crate) fn call_data(&mut self, f: &crate::heap::DataFn, name: &Rc, this: &Value, args: &[Value], how: &ArgRead) -> JsResult { let data = match how { ArgRead::Site => site_data(self.call_site()), - ArgRead::Hosted => { - let this = match this { - Value::Object(o) => self.host_ref_of(*o)?.unwrap_or(Data::Undefined), - _ => Data::Undefined, - }; - let mut data = vec![this]; - data.extend(self.read_args(name, args, how)?); - data - } - _ => self.read_args(name, args, how)?, + ArgRead::Hosted => self.read_args(name, Some(this), args, how)?, + _ => self.read_args(name, None, args, how)?, }; // Only the script's own code, in a run that can pause, can wait for a result, and a host // class's constructor called with `new` cannot. @@ -463,7 +462,7 @@ impl Interp { name: &Rc, args: &[Value], ) -> JsResult { - let data = self.read_args(name, args, &ArgRead::Data)?; + let data = self.read_args(name, None, args, &ArgRead::Data)?; let source = match f(data) { Ok(Data::String(source)) => source, Ok(d) => return self.write_data(d, 0, false), @@ -505,8 +504,8 @@ impl Interp { r } - /// The arguments of host function `name` as [`Data`], read as `how` says. - fn read_args(&mut self, name: &Rc, args: &[Value], how: &ArgRead) -> JsResult> { + /// The arguments of host function `name` as [`Data`], read as `how` says, with an optional host receiver first. + fn read_args(&mut self, name: &Rc, this: Option<&Value>, args: &[Value], how: &ArgRead) -> JsResult> { let mut reading = Reading { limits: self.data_limits, bytes: 0, @@ -520,7 +519,14 @@ impl Interp { ArgRead::Each(list) => args.get(..list.len().min(args.len())).unwrap_or(args), _ => args, }; - let mut data = Vec::with_capacity(args.len()); + let mut data = Vec::with_capacity(args.len() + 1); + if let Some(this) = this { + let this = match this { + Value::Object(o) if self.host_ref_size(*o)?.is_some() => self.read_host_ref(*o, &mut reading)?, + _ => Data::Undefined, + }; + data.push(this); + } // A conversion can run the script's own `toString`, which may collect garbage. let mark = self.temp_roots.len(); if !matches!(how, ArgRead::Data | ArgRead::Frozen | ArgRead::Hosted) { @@ -552,6 +558,29 @@ impl Interp { Ok(data) } + pub(crate) fn read_index_args(&mut self, id: ObjId, key: Data, probe: bool) -> JsResult> { + let mut reading = Reading { + limits: self.data_limits, + bytes: 0, + entries: 0, + ancestors: Vec::new(), + path: Vec::new(), + function: Rc::from("host indexer"), + hosted: true, + }; + let receiver = self.read_host_ref(id, &mut reading)?; + match &key { + Data::String(s) => self.charge_reading(&mut reading, s.encode_utf16().count().saturating_mul(3).saturating_add(2))?, + Data::Number(_) => {} + _ => return Err(Abrupt::Internal("a host indexer key is not a number or string".into())), + } + let mut args = vec![receiver, key]; + if probe { + args.push(Data::Bool(true)); + } + Ok(args) + } + /// What host error `e` throws, or the limit it ends the run with. A function that waits /// ([`HostError::Wait`]) where its caller does not handle the wait ends the run with an internal /// error. diff --git a/crates/js/src/host_classes.rs b/crates/js/src/host_classes.rs index d2994fb80b..9d14718dee 100644 --- a/crates/js/src/host_classes.rs +++ b/crates/js/src/host_classes.rs @@ -172,6 +172,12 @@ impl Interp { Ok(Some(host_ref(&name, &h.handle))) } + pub(crate) fn host_ref_size(&self, id: ObjId) -> JsResult> { + let Class::Host(h) = &self.object(id)?.class else { return Ok(None) }; + let name = self.host_classes.get(h.class as usize).map(|e| e.name.len()).ok_or_else(|| Abrupt::Internal("host class out of range".into()))?; + Ok(Some((name, h.handle.len()))) + } + /// The object of a host class that `d`, which a host function gave, stands for. pub(crate) fn write_host_ref(&mut self, d: &Data) -> JsResult { let Some((name, handle)) = host_ref_parts(d) else { @@ -220,11 +226,10 @@ impl Interp { /// gets `true` as a third argument. pub(crate) fn host_index(&mut self, f: &HostFunction, id: ObjId, k: Data, probe: bool) -> JsResult { self.use_fuel()?; - let Some(this) = self.host_ref_of(id)? else { return Ok(Value::Undefined) }; - let mut args = vec![this, k]; - if probe { - args.push(Data::Bool(true)); + if self.host_ref_size(id)?.is_none() { + return Ok(Value::Undefined); } + let args = self.read_index_args(id, k, probe)?; match f(args) { Ok(d) => self.write_hosted(d), Err(HostError::Wait) => Err(Abrupt::Internal("a host class's indexer waited for its result".into())), diff --git a/crates/js/src/host_tests.rs b/crates/js/src/host_tests.rs index 25265086e5..1d199fb16c 100644 --- a/crates/js/src/host_tests.rs +++ b/crates/js/src/host_tests.rs @@ -11,6 +11,54 @@ fn realm(fuel: u64) -> Realm { r } +#[test] +fn non_finite_indexer_keys_reach_the_host_unchanged() { + let mut r = realm(1_000_000); + let index: HostFunction = Rc::new(|args| Ok(Data::Bool(matches!(args.get(1), Some(Data::Number(n)) if !n.is_finite())))); + let class = HostClass { name: "Indexed".into(), parent: None, members: vec![], index: Some(index), construct: None }; + r.define_host_classes(vec![class], vec![("it".into(), host_ref("Indexed", &[1.0]))]).unwrap(); + let source = "[it[NaN], it[Infinity], it[-Infinity], NaN in it, Infinity in it, -Infinity in it].join('|')"; + assert_eq!(r.run(source).unwrap(), JsValue::String("true|true|true|true|true|true".into())); +} + +#[test] +fn host_receivers_obey_limits_lowered_after_the_object_was_created() { + for limits in [DataLimits { depth: 64, bytes: 1_000, entries: 2 }, DataLimits { depth: 64, bytes: 1, entries: 100 }] { + for expression in ["it[0]", "0 in it", "it.method()", "it.take(it)"] { + let mut r = realm(1_000_000); + let calls = Rc::new(Cell::new(0)); + let called = calls.clone(); + let function: HostFunction = Rc::new(move |_| { + called.set(called.get() + 1); + Ok(Data::Undefined) + }); + let class = HostClass { + name: "Indexed".into(), + parent: None, + members: vec![("method".into(), HostMember::Method(function.clone())), ("take".into(), HostMember::Method(function.clone()))], + index: Some(function), + construct: None, + }; + r.define_host_classes(vec![class], vec![("it".into(), host_ref("Indexed", &[1.0, 2.0, 3.0]))]).unwrap(); + r.set_data_limits(limits); + let source = format!("var result = 'called'; try {{ {expression}; }} catch (e) {{ result = e.name; }} result"); + assert_eq!(r.run(&source).unwrap(), JsValue::String("RangeError".into()), "{expression}: {limits:?}"); + assert_eq!(calls.get(), 0, "{expression}"); + } + } +} + +#[test] +fn index_keys_share_the_receivers_data_budget() { + let mut r = realm(1_000_000); + let class = HostClass { name: "Indexed".into(), parent: None, members: vec![], index: Some(Rc::new(|_| Ok(Data::Bool(true)))), construct: None }; + r.define_host_classes(vec![class], vec![("it".into(), host_ref("Indexed", &[1.0]))]).unwrap(); + r.set_data_limits(DataLimits { depth: 64, bytes: 256, entries: 100 }); + assert_eq!(r.run("it['short']").unwrap(), JsValue::Bool(true)); + let source = "var result = 'called'; try { it[new Array(200).join('x')]; } catch (e) { result = e.name; } result"; + assert_eq!(r.run(source).unwrap(), JsValue::String("RangeError".into())); +} + /// A realm with `host.take(value)`, which records what it was given and returns it. fn with_take(r: &mut Realm) -> Rc>> { let seen: Rc>> = Rc::default(); From 10c8cba547a212aac504df4bf75bf1270f75fef4 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 26 Nov 2026 09:45:56 -0800 Subject: [PATCH 127/151] Keep Swatches list drags in the document that started them --- crates/ui-egui/src/panel_drag.rs | 2 + crates/ui-egui/src/panels/swatches.rs | 9 ++-- crates/ui-egui/src/panels/swatches/dnd.rs | 7 +-- crates/ui-egui/src/panels/swatches/tests.rs | 56 ++++++++++++++++++++- 4 files changed, 66 insertions(+), 8 deletions(-) diff --git a/crates/ui-egui/src/panel_drag.rs b/crates/ui-egui/src/panel_drag.rs index 83ebf46070..27cab1fe2c 100644 --- a/crates/ui-egui/src/panel_drag.rs +++ b/crates/ui-egui/src/panel_drag.rs @@ -41,6 +41,8 @@ pub enum PanelDrag { /// panel order. #[derive(Clone, Debug, PartialEq)] pub struct SwatchRows { + /// The document whose rows the drag started on. + pub document: u64, pub grabbed: String, pub names: Vec, /// The names are colour groups. diff --git a/crates/ui-egui/src/panels/swatches.rs b/crates/ui-egui/src/panels/swatches.rs index 58f24ed3f5..bb8eaa994f 100644 --- a/crates/ui-egui/src/panels/swatches.rs +++ b/crates/ui-egui/src/panels/swatches.rs @@ -409,8 +409,8 @@ fn body(app: &mut VectorcraftApp, ui: &mut Ui) { let dragged_doc = Arc::clone(&thumbs.doc); let document = st.uid; let shown_app: &VectorcraftApp = app; - let out = SwatchesPanel::new(&data, Bind::bound(&mut model.state), Srgba::rgb(0.0, 0.0, 0.0)) - .drag_payload(move |drag: &ListDrag| Some(dnd::drag_of(&dragged_doc, &drag.grabbed, dragged_rows(drag)))) + let browser = SwatchesPanel::new(&data, Bind::bound(&mut model.state), Srgba::rgb(0.0, 0.0, 0.0)) + .drag_payload(move |drag: &ListDrag| Some(dnd::drag_of(&dragged_doc, document, &drag.grabbed, dragged_rows(drag)))) .thumb(thumbs, thumb) .row_icons(|key| match key { SwatchKey::Swatch(name) => row_icons(shown_app, name), @@ -422,8 +422,9 @@ fn body(app: &mut VectorcraftApp, ui: &mut Ui) { .select(SelectMode::Multi) .search(model.show_find) .reveal(focus.map(SwatchKey::Swatch)) - .footer(None) - .show(ui); + .footer(None); + // A list drag is keyed by its browser ID. Each document has its own browser. + let out = ui.push_id(("swatch-rows", document), |ui| browser.show(ui)).inner; app.ui.swatches_panel = model; let shown = shown_keys(&data); if let Some((at, _, alt)) = out.used diff --git a/crates/ui-egui/src/panels/swatches/dnd.rs b/crates/ui-egui/src/panels/swatches/dnd.rs index 2151357979..f4d100f2d6 100644 --- a/crates/ui-egui/src/panels/swatches/dnd.rs +++ b/crates/ui-egui/src/panels/swatches/dnd.rs @@ -4,9 +4,10 @@ use craft::color_ui::ui::SwatchKey; use craft::keymap::Mods; use craft::ui::contract::{DropAt, ReorderMove}; -/// Swatches take paint payloads and artwork from the current document's canvas. +/// Swatches take paints, and take swatch rows or canvas art from the current document. pub(super) fn accepts(drag: &PanelDrag, document: u64) -> bool { match drag { + PanelDrag::Paint { rows: Some(rows), .. } => rows.document == document, PanelDrag::Paint { .. } => true, PanelDrag::Art { document: source, .. } => *source == document, _ => false, @@ -53,7 +54,7 @@ impl Drop { /// The drag a row of `key` starts, moving rows `names`. Colour groups have no paint of their own /// (the chip under the pointer draws Registration's mark for Registration). -pub(super) fn drag_of(d: &Document, key: &SwatchKey, names: Vec) -> PanelDrag { +pub(super) fn drag_of(d: &Document, document: u64, key: &SwatchKey, names: Vec) -> PanelDrag { let name = name_of(key); let (paint, params) = match key { SwatchKey::Swatch(_) if name == REGISTRATION => (Paint::registration(), swatch_params(d, name)), @@ -63,7 +64,7 @@ pub(super) fn drag_of(d: &Document, key: &SwatchKey, names: Vec) -> Pane }, _ => (Paint::None, Value::Null), }; - let rows = SwatchRows { grabbed: name.to_string(), names, groups: matches!(key, SwatchKey::Group(_)) }; + let rows = SwatchRows { document, grabbed: name.to_string(), names, groups: matches!(key, SwatchKey::Group(_)) }; PanelDrag::Paint { paint, params, rows: Some(rows), library: None } } diff --git a/crates/ui-egui/src/panels/swatches/tests.rs b/crates/ui-egui/src/panels/swatches/tests.rs index c770f5094a..0e5387e547 100644 --- a/crates/ui-egui/src/panels/swatches/tests.rs +++ b/crates/ui-egui/src/panels/swatches/tests.rs @@ -96,7 +96,61 @@ fn dropped_below(app: &mut VectorcraftApp, drag: PanelDrag, mods: Mods) { /// The drag the row `name` starts, carrying rows `names`. fn rows_drag(app: &VectorcraftApp, name: &str, names: &[&str]) -> PanelDrag { - dnd::drag_of(&doc(app), &key_of(app, name), names.iter().map(|n| n.to_string()).collect()) + let document = app.session.active().unwrap().uid; + dnd::drag_of(&doc(app), document, &key_of(app, name), names.iter().map(|n| n.to_string()).collect()) +} + +#[test] +fn a_swatch_row_drag_reorders_only_its_source_document() { + use crate::tests::panel_harness::Panel; + use craft::ui::contract::{ListDrag, Role}; + use craft::ui::runtime::drag; + use egui::{Key, Modifiers}; + + let mut app = app(); + let source = app.session.active().unwrap().uid; + let before_source = names_of(&app, None); + app.run("file.new", json!({"width": 200, "height": 200})).unwrap(); + let destination = app.session.active().unwrap().uid; + let before_destination = names_of(&app, None); + app.run("window.previousDocument", json!({})).unwrap(); + assert_eq!(app.session.active().unwrap().uid, source); + + let mut panel = Panel::new(app, show); + let drag_red = |panel: &mut Panel| { + let red = "Red, #ed1c24"; + let from = panel.rect(red).center(); + let to = panel.rect("Green, #39b54a").center(); + panel.drag_hold_role(red, Role::LIST_ITEM, to - from); + let grabbed = drag::active::>(panel.ctx()).map(|d| d.grabbed.clone()); + assert_eq!(grabbed, Some(SwatchKey::Swatch("Red".into()))); + }; + drag_red(&mut panel); + panel.key(Key::F6, Modifiers::COMMAND); + assert_eq!(panel.app().session.active().unwrap().uid, destination); + panel.release(); + assert_eq!(names_of(&panel.app(), None), before_destination); + + panel.key(Key::F6, Modifiers::COMMAND); + assert_eq!(panel.app().session.active().unwrap().uid, source); + assert_eq!(names_of(&panel.app(), None), before_source); + drag_red(&mut panel); + panel.release(); + assert_ne!(names_of(&panel.app(), None), before_source); + panel.app().run("edit.undo", json!({})).unwrap(); + assert_eq!(names_of(&panel.app(), None), before_source); +} + +#[test] +fn a_foreign_swatch_row_payload_cannot_move_or_replace_local_swatches() { + let mut app = app(); + let drag = rows_drag(&app, "Red", &["Red"]); + app.run("file.new", json!({"width": 200, "height": 200})).unwrap(); + let before = doc(&app); + assert!(!dnd::accepts(&drag, app.session.active().unwrap().uid)); + dropped_below(&mut app, drag.clone(), none()); + dropped(&mut app, drag, "Green", alt()); + assert_eq!(doc(&app).swatches, before.swatches); } /// Art `ids` dragged off the canvas. From 293a7d2cb1616f79bb66dc16dfc825937b996b54 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 26 Nov 2026 09:57:51 -0800 Subject: [PATCH 128/151] Disambiguate the color checksum dependency in Cargo.lock --- Cargo.lock | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Cargo.lock b/Cargo.lock index 653aa64e73..905d33b8fc 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -8480,7 +8480,7 @@ dependencies = [ "proptest", "serde", "serde_json", - "sha2", + "sha2 0.10.9", "thiserror 2.0.21", ] From 237f97b87b12cdfb89216281fa1a1cf01dedca6c Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 26 Nov 2026 10:06:49 -0800 Subject: [PATCH 129/151] Keep CSS Properties actions reachable in short panels --- crates/ui-egui/src/panels/css_properties.rs | 97 ++++++++++++++++----- 1 file changed, 74 insertions(+), 23 deletions(-) diff --git a/crates/ui-egui/src/panels/css_properties.rs b/crates/ui-egui/src/panels/css_properties.rs index b3e8833076..91683cc016 100644 --- a/crates/ui-egui/src/panels/css_properties.rs +++ b/crates/ui-egui/src/panels/css_properties.rs @@ -10,7 +10,7 @@ use std::sync::Arc; use craft::behavior::IconId; use craft::keymap::CommandRef; use craft::theme::variant::Tone; -use craft::ui::contract::{Scroll, Show as _, ShowContainer as _}; +use craft::ui::contract::{Props as _, Scroll, Show as _, ShowContainer as _}; use craft::ui::display::{Shade, Text}; use craft::ui::layout_components::Stack; use craft::ui::menu::PanelRow; @@ -132,19 +132,7 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { let opts = app.ui.css_properties_panel.options.clone(); let all = !selected && app.ui.css_properties_panel.all; let Some(shown) = shown(app, &opts, all) else { return }; - Stack::new().fill().surface(SurfaceKind::Well).scroll(Scroll::both()).show(ui, |ui, _| { - let globe = NoticeIcon::Custom(IconSpec::svg(IconId::new("globe"))); - if shown.rules > 0 { - SelectableText::spans(tl!("CSS code"), spans(&shown.text)).mono().multiline().show(ui); - } else if selected { - let hint = tl!("The selected objects have no CSS of their own (see below)."); - Notice::new(Tone::Neutral, hint).title(tl!("No CSS")).layout(NoticeLayout::Centred).icon(globe).show(ui); - } else { - let hint = tl!("Select objects to see their CSS, or Generate CSS for the whole document."); - Notice::new(Tone::Neutral, hint).title(tl!("No selection")).layout(NoticeLayout::Centred).icon(globe).show(ui); - } - }); - let notes = (shown.more > 0) + let notes: Vec<_> = (shown.more > 0) .then(|| crate::i18n::tn(shown.more as u64, "{n} more rule: Export writes it.", "{n} more rules: Export writes every one.")) .into_iter() .chain((shown.skipped > 0).then(|| { @@ -154,23 +142,50 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { "{n} unnamed objects left out: name them, or turn on Unnamed Objects in the panel menu.", ) })) - .chain(shown.warnings.iter().map(|w| sentence(w))); - for n in notes { - Text::new(n).role(TypeRole::Caption).shade(Shade::Muted).show(ui); - } + .chain(shown.warnings.iter().map(|w| sentence(w))) + .collect(); let has_css = shown.rules > 0; let scope = if all { "all" } else { "selection" }; // Generate at the start edge; Export at the end edge with Copy before it. - let footer = FooterBar::actions([ + let actions = [ FooterAction::new(IconId::new("sparkles"), tl!("Generate CSS: the whole document's CSS while nothing is selected")) .pressed(all) .enabled(!selected), FooterAction::new(IconId::new("save"), if all { tl!("Export All…") } else { tl!("Export Selected CSS…") }).enabled(has_css), FooterAction::new(IconId::new("copy"), if all { tl!("Copy All Styles") } else { tl!("Copy Selected Style") }).enabled(has_css), - ]) - .at_start(1) - .show_footer(ui); - match footer.picked { + ]; + let mut picked = None; + let notes_room = (ui.available_height() / 3.0).min(72.0); + Stack::new() + .fill() + .footer(|ui, _| { + if !notes.is_empty() { + Stack::new().label(tl!("Notes")).fill_width().scroll(Scroll::vertical()).room_height(notes_room).show(ui, |ui, _| { + for note in ¬es { + Text::new(note.clone()).role(TypeRole::Caption).shade(Shade::Muted).show(ui); + } + }); + } + let footer = FooterBar::actions(actions.clone()).at_start(1).show_footer(ui); + if !ui.is_sizing_pass() { + picked = footer.picked; + } + }) + .show(ui, |ui, _| { + Stack::new().label(tl!("CSS Properties")).fill().surface(SurfaceKind::Well).scroll(Scroll::both()).show(ui, |ui, _| { + let globe = NoticeIcon::Custom(IconSpec::svg(IconId::new("globe"))); + if shown.rules > 0 { + SelectableText::spans(tl!("CSS code"), spans(&shown.text)).mono().multiline().show(ui); + } else if selected { + let hint = tl!("The selected objects have no CSS of their own (see below)."); + Notice::new(Tone::Neutral, hint).title(tl!("No CSS")).layout(NoticeLayout::Centred).icon(globe).show(ui); + } else { + let hint = tl!("Select objects to see their CSS, or Generate CSS for the whole document."); + Notice::new(Tone::Neutral, hint).title(tl!("No selection")).layout(NoticeLayout::Centred).icon(globe).show(ui); + } + }); + }); + match picked { Some(0) => { crate::menus::invoke(app, GENERATE, json!({})); } @@ -311,3 +326,39 @@ pub(crate) fn run(app: &mut VectorcraftApp, id: &str, p: &Value) -> Option return None, }) } + +#[cfg(test)] +mod tests { + use super::*; + use crate::tests::panel_harness::Panel; + use vectorcraft_engine::Session; + + #[test] + fn generated_css_notices_keep_the_actions_in_a_short_panel() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({ "width": 100, "height": 100 })).unwrap(); + for card in 0..12 { + let id = app.run("shape.rectangle", json!({ "x": 0, "y": 0, "width": 20, "height": 20 })).unwrap()["id"].clone(); + app.run("layer.setProps", json!({ "id": id, "name": format!("Card-{card}") })).unwrap(); + } + app.run("shape.ellipse", json!({ "x": 30, "y": 0, "width": 20, "height": 20 })).unwrap(); + app.run("select.none", json!({})).unwrap(); + let options = CssOptions { unnamed: false, ..CssOptions::default() }; + let styles = shown(&mut app, &options, true).unwrap(); + assert_eq!((styles.rules, styles.skipped), (12, 1)); + app.ui.css_properties_panel = CssPropertiesPanel { options, all: true }; + + let mut panel = Panel::new(app, show); + let room = egui::vec2(220.0, 220.0); + panel.room(room).frame(); + panel.frame(); + for name in ["Copy All Styles", "Export All…"] { + let action = panel.rect(name); + assert!(action.bottom() <= room.y && action.right() <= room.x, "{name} overflows the panel at {action:?}"); + assert!(panel.enabled(name), "{name} is enabled when there is CSS"); + } + let notice = panel.rect("1 unnamed object left out: name it, or turn on Unnamed Objects in the panel menu."); + assert!(notice.top() >= 0.0 && notice.bottom() <= panel.rect("Copy All Styles").top(), "the notice fits above the actions: {notice:?}"); + assert!(notice.left() >= 0.0 && notice.right() <= room.x, "the notice wraps within the panel: {notice:?}"); + } +} From a3c6e29d9decbc300a7ee27f8c73abb58320684c Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 26 Nov 2026 10:12:32 -0800 Subject: [PATCH 130/151] Cover switching away from an unfinished pattern rename --- crates/ui-egui/src/panels/pattern_options.rs | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/crates/ui-egui/src/panels/pattern_options.rs b/crates/ui-egui/src/panels/pattern_options.rs index d958f72b86..93e93681f2 100644 --- a/crates/ui-egui/src/panels/pattern_options.rs +++ b/crates/ui-egui/src/panels/pattern_options.rs @@ -302,5 +302,11 @@ mod tests { assert_eq!(panel.value("Name").as_deref(), Some("Dots")); panel.key(egui::Key::Enter, egui::Modifiers::NONE); assert!(panel.app().session.active().unwrap().doc.pattern("Dots").is_some()); + + panel.app().run("window.previousDocument", json!({})).unwrap(); + panel.frame(); + assert_eq!(panel.app().session.active().unwrap().uid, source); + assert_eq!(panel.value("Name").as_deref(), Some("Dots")); + assert!(panel.app().session.active().unwrap().doc.pattern("Dots").is_some()); } } From dfa6bae8eb69fb00ae56e35b72f0c77664c4cb1e Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 26 Nov 2026 10:27:23 -0800 Subject: [PATCH 131/151] Strengthen host indexer argument and shared-budget assertions --- crates/js/src/host_tests.rs | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/crates/js/src/host_tests.rs b/crates/js/src/host_tests.rs index 125ff9c43b..8c4b036898 100644 --- a/crates/js/src/host_tests.rs +++ b/crates/js/src/host_tests.rs @@ -14,7 +14,10 @@ fn realm(fuel: u64) -> Realm { #[test] fn non_finite_indexer_keys_reach_the_host_unchanged() { let mut r = realm(1_000_000); - let index: HostFunction = Rc::new(|args| Ok(Data::Bool(matches!(args.get(1), Some(Data::Number(n)) if !n.is_finite())))); + let index: HostFunction = Rc::new(|args| { + assert!(matches!(args.get(1), Some(Data::Number(n)) if !n.is_finite()), "{args:?}"); + Ok(Data::Bool(true)) + }); let class = HostClass { name: "Indexed".into(), parent: None, members: vec![], index: Some(index), construct: None }; r.define_host_classes(vec![class], vec![("it".into(), host_ref("Indexed", &[1.0]))]).unwrap(); let source = "[it[NaN], it[Infinity], it[-Infinity], NaN in it, Infinity in it, -Infinity in it].join('|')"; @@ -55,7 +58,7 @@ fn index_keys_share_the_receivers_data_budget() { r.define_host_classes(vec![class], vec![("it".into(), host_ref("Indexed", &[1.0]))]).unwrap(); r.set_data_limits(DataLimits { depth: 64, bytes: 256, entries: 100 }); assert_eq!(r.run("it['short']").unwrap(), JsValue::Bool(true)); - let source = "var result = 'called'; try { it[new Array(200).join('x')]; } catch (e) { result = e.name; } result"; + let source = "var result = 'called'; try { it[new Array(71).join('x')]; } catch (e) { result = e.name; } result"; assert_eq!(r.run(source).unwrap(), JsValue::String("RangeError".into())); } From ca687534636d03d6cd6389318e8186b13c252da6 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 26 Nov 2026 10:37:22 -0800 Subject: [PATCH 132/151] Keep startup queue failures and stop requests consistent --- crates/engine/src/cmd/scripts.rs | 15 ++-- crates/engine/src/script/mod.rs | 2 +- crates/engine/tests/script_startup.rs | 99 ++++++++++++++++++++++++++- docs/mcp.md | 3 + docs/target-app-parity.md | 2 +- 5 files changed, 112 insertions(+), 9 deletions(-) diff --git a/crates/engine/src/cmd/scripts.rs b/crates/engine/src/cmd/scripts.rs index d92f654888..93eee5c5c0 100644 --- a/crates/engine/src/cmd/scripts.rs +++ b/crates/engine/src/cmd/scripts.rs @@ -95,7 +95,7 @@ pub fn specs() -> Vec { "Run Startup Scripts", [], None, - "{reason: launch|menu (launch: the app starting; menu: before a script chosen from File › Scripts), then?: script.run's parameters (the script to run once the startup scripts have run; its source is read once and must compile before enabled startup scripts run), maxFuel?: whole number from 1 to 100000000000 (each startup script's instructions; default 1000000000)} run the .jsx files of the Startup Scripts folder next to the settings, one at a time, as script.run runs a file, each with the same limits as any script and its own undo step; nothing runs, and the reply says why, when the runStartupScripts preference is off (the default), in Safe Mode, or in a session without the folder (the web, and a run with VECTORCRAFT_NO_PREFS); only the folder's own .jsx files run, sorted by name without regard to case, then by name; links, hidden files, names starting with a dot, subfolders and other files are left out, and so is a script the Safe Mode choice disabled; a missing folder runs nothing; a script that cannot be read, is larger than 8 MiB, fails or is stopped is named in failed and in the Script Console, and the next one runs, then the script of then; while a startup script runs, the launch marker names it, so a launch that stops there offers to disable it; script.* commands are refused inside a script, so a startup script does not start another startup run. VectorCraft's own rules: the folder, the order, the limits of a listing (2048 folder entries, 512 scripts, 250 ms) and what a failure does → {reason, skipped: true, why: off|safeMode|noFolder, then?: script.run's reply} | {reason, skipped: false, ran: [names], failed: [{name, error}], disabled: [names], truncated, unreadable, then?: script.run's reply}, or, in the app, {reason, skipped: false, running, queued: the runs queued, then's included, failed: [{name, error}] (the runs that could not start before the first one did), disabled, truncated, unreadable, then?: script.run's reply when it ran to its end at once}, each run then reporting as script.run's do, and a later run that cannot start is named in the status bar, where the message of a startup script that fails or is stopped also stays", + "{reason: launch|menu (launch: the app starting; menu: before a script chosen from File › Scripts), then?: script.run's parameters (the script to run once the startup scripts have run; its source is read once and must compile before enabled startup scripts run), maxFuel?: whole number from 1 to 100000000000 (each startup script's instructions; default 1000000000)} run the .jsx files of the Startup Scripts folder next to the settings, one at a time, as script.run runs a file, each with the same limits as any script and its own undo step; nothing runs, and the reply says why, when the runStartupScripts preference is off (the default), in Safe Mode, or in a session without the folder (the web, and a run with VECTORCRAFT_NO_PREFS); only the folder's own .jsx files run, sorted by name without regard to case, then by name; links, hidden files, names starting with a dot, subfolders and other files are left out, and so is a script the Safe Mode choice disabled; a missing folder runs nothing; a script that cannot be read, is larger than 8 MiB, fails or is stopped is named in failed and in the Script Console, and the next one runs, then the script of then; while a startup script runs, the launch marker names it, so a launch that stops there offers to disable it; script.* commands are refused inside a script, so a startup script does not start another startup run. VectorCraft's own rules: the folder, the order, the limits of a listing (2048 folder entries, 512 scripts, 250 ms) and what a failure does → {reason, skipped: true, why: off|safeMode|noFolder, then?: script.run's reply} | {reason, skipped: false, ran: [names], failed: [{name, error}], disabled: [names], truncated, unreadable, then?: script.run's reply}, or, in the app, {reason, skipped: false, running, queued: the runs queued, then's included, failed: [{name, error}] (the runs that could not start before the first one did), disabled, truncated, unreadable, then?: script.run's reply when it ran to its end at once}, each run then reporting as script.run's do, and a later run that cannot start is named in the status bar, where the message of a startup script that fails or is stopped also stays; included files are read again when the chosen run starts; a preflight compilation failure clears the previous script report; each app queue pump processes at most one startup entry", always, startup_run ), @@ -460,7 +460,7 @@ impl Session { /// With no script running, starts the next run `script.startup.run` queued: the next startup /// script that starts, or the script queued after them. A run that cannot start is kept for - /// [`Self::take_startup_failures`], and the next one starts. → the reply of the script queued + /// [`Self::take_startup_failures`], and the next one starts on a later pump. → the reply of the script queued /// after them when it ran to its end at once. pub(crate) fn start_queued(&mut self) -> Option { // Held aside while a run starts, so that the queue does not count as a running script then. @@ -469,8 +469,9 @@ impl Session { // keeps, and not in the scope of the frame that starts it. let scope = self.script_queue_scope.clone().unwrap_or_else(crate::file_access::ScopeHandle::capture); let mut reply = None; - while self.script_key.is_none() { - let Some(next) = queue.pop_front() else { break }; + if self.script_key.is_none() + && let Some(next) = queue.pop_front() + { match next { script::startup::Queued::Startup { path, fuel } => { if let Err(e) = scope.clone().run(|| self.start_startup(&path, fuel)) { @@ -487,7 +488,6 @@ impl Session { Ok(v) => reply = Some(v), Err(e) => self.startup_failures.push((then_name(¶ms), e.to_string())), } - break; } } } @@ -573,7 +573,10 @@ fn startup_run(s: &mut Session, p: &Value) -> Result { let prepared = then.as_ref().map(|params| prepare(s, params)).transpose()?; if let Some(request) = &prepared { let mut preflight = Session::new(); - preflight.script_start(request.clone())?; + if let Err(error) = preflight.script_start(request.clone()) { + s.script_report = None; + return Err(error); + } } let folder = root.to_string_lossy().into_owned(); // The folder is the app's: a refusal names it as the request may see it. diff --git a/crates/engine/src/script/mod.rs b/crates/engine/src/script/mod.rs index 55c5ebcd1a..c5fffb6574 100644 --- a/crates/engine/src/script/mod.rs +++ b/crates/engine/src/script/mod.rs @@ -2224,7 +2224,7 @@ impl Session { // A stop asked for between two runs stops the run that starts now, which clears it. let stop = self.script_stop.is_set(); self.start_queued(); - if stop && self.script_key.is_some() { + if stop && (self.script_key.is_some() || !self.script_queue.is_empty()) { self.script_stop.set(); } else { self.script_stop.clear(); diff --git a/crates/engine/tests/script_startup.rs b/crates/engine/tests/script_startup.rs index 24c14113de..527374c9f6 100644 --- a/crates/engine/tests/script_startup.rs +++ b/crates/engine/tests/script_startup.rs @@ -293,6 +293,99 @@ fn a_chosen_script_that_cannot_start_is_refused_before_any_startup_script_runs() } } +#[test] +fn a_stop_between_runs_survives_an_entry_that_cannot_start() { + let _f = fresh(); + let dir = tmp_dir("stop-before-failed-entry"); + write(&dir, "a.jsx", "vc.log('first');"); + write(&dir, "b.jsx", "var = ;"); + write(&dir, "c.jsx", "vc.log('must not run');"); + for by_interrupt in [false, true] { + let mut s = session(&dir); + s.script_frames = true; + s.execute("script.startup.run", &json!({"reason": "launch"})).unwrap(); + assert!((0..10_000).find_map(|_| s.script_pump()).unwrap().is_ok()); + if by_interrupt { + s.script_interrupt().set(); + } else { + assert!(s.script_request_stop()); + } + let stopped = (0..10_000).find_map(|_| s.script_pump()).unwrap(); + assert!(stopped.is_err(), "by_interrupt={by_interrupt}"); + assert_eq!(s.script_report().unwrap()["name"], "c.jsx"); + assert_eq!(s.script_report().unwrap()["kind"], "stopped"); + assert_eq!(console(&s, "log"), ["first"]); + assert_eq!(s.take_startup_failures().iter().map(|(name, _)| name.as_str()).collect::>(), ["b.jsx"]); + } +} + +#[test] +fn the_chosen_run_reads_includes_after_the_startup_runs() { + let _f = fresh(); + let dir = tmp_dir("chosen-includes"); + let startup = dir.join("startup"); + let chosen = dir.join("chosen"); + write(&startup, "a.jsx", "vc.log('startup');"); + let include = write(&chosen, "value.jsxinc", "vc.log('before');"); + let main = write(&chosen, "main.jsx", "#include \"value.jsxinc\"\nvc.log('main');"); + let mut s = session(&startup); + s.script_frames = true; + s.execute("script.startup.run", &json!({"reason": "menu", "then": {"path": main.to_string_lossy()}})).unwrap(); + std::fs::write(&include, "vc.log('after');").unwrap(); + for _ in 0..1000 { + if !s.script_running() { + break; + } + s.script_pump(); + } + assert!(!s.script_running()); + assert_eq!(console(&s, "log"), ["startup", "after", "main"]); +} + +#[test] +fn failed_startup_entries_resume_in_fifo_order_on_later_pumps() { + let _f = fresh(); + let dir = tmp_dir("failed-startup-pumps"); + for name in ["a.jsx", "b.jsx", "c.jsx"] { + write(&dir, name, "var = ;"); + } + let mut s = session(&dir); + s.script_frames = true; + let first = s.execute("script.startup.run", &json!({"reason": "menu", "then": {"source": "vc.log('chosen');", "name": "chosen"}})).unwrap(); + let failures = first["failed"].as_array().unwrap(); + assert!(!failures.is_empty() && failures.len() < 3, "{first}"); + assert!(!started(&s).iter().any(|name| name == "chosen"), "the chosen run follows the remaining startup entries"); + let mut failed: Vec = failures.iter().map(|entry| entry["name"].as_str().unwrap().to_string()).collect(); + for _ in 0..100 { + if !s.script_running() { + break; + } + s.script_pump(); + failed.extend(s.take_startup_failures().into_iter().map(|(name, _)| name)); + } + assert!(!s.script_running()); + assert_eq!(failed, ["a.jsx", "b.jsx", "c.jsx"]); + assert_eq!(console(&s, "log"), ["chosen"]); +} + +#[test] +fn a_failed_chosen_preflight_clears_the_previous_report() { + let _f = fresh(); + let dir = tmp_dir("preflight-report"); + write(&dir, "a.jsx", "vc.log('startup');"); + for frames in [false, true] { + let mut s = session(&dir); + s.execute("script.run", &json!({"source": "vc.log('previous');"})).unwrap(); + assert!(s.script_report().is_some()); + let before = started(&s); + s.script_frames = frames; + assert!(s.execute("script.startup.run", &json!({"reason": "menu", "then": {"source": "var = ;"}})).is_err()); + assert!(s.script_report().is_none(), "frames={frames}"); + assert_eq!(started(&s), before); + assert!(!s.script_running()); + } +} + #[test] fn a_chosen_script_with_invalid_syntax_is_refused_before_startup_scripts_run() { let _f = fresh(); @@ -461,9 +554,13 @@ fn in_the_app_every_queued_run_keeps_the_automation_roots_of_the_request_that_qu let r = if confined { vectorcraft_engine::file_access::confine(Some(&roots), request) } else { request() }; assert_eq!(r["queued"], json!(3)); // The frames that start the later runs are outside the request. - while s.script_running() { + for _ in 0..1000 { + if !s.script_running() { + break; + } s.script_pump(); } + assert!(!s.script_running(), "the startup queue did not finish, confined {confined}"); assert_eq!(started(&s), ["a.jsx", "b.jsx", "chosen"]); let want = if confined { "refused" } else { "wrote" }; assert_eq!(console(&s, "log"), [want, want, want], "confined {confined}"); diff --git a/docs/mcp.md b/docs/mcp.md index 0c94652c3e..1f36c3731e 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -3518,6 +3518,9 @@ parameters for a script that runs after the startup scripts. A `then` that `scri missing file, one larger than 8 MiB, or source that fails to compile, ends the request with `script.run`'s error before any startup script runs. Compilation does not execute the chosen script. The chosen script runs the source read before startup scripts begin, including when a startup script removes the installed file. +Included files are read again when the chosen run starts, so edits to them during startup affect that run. +A failed chosen-script compilation clears the previous script report. In the app, each queue pump processes at +most one startup entry and keeps later entries in order, including after a startup entry fails. `maxFuel` limits each startup script's instructions (from 1 to 100,000,000,000, default 1,000,000,000). It returns `{reason, skipped: true, why}` with `why` set to `off`, `safeMode` or `noFolder` when nothing runs, and otherwise `{reason, skipped: false, ran, failed: [{name, error}], diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 7fc3ba6a74..2d9e73f525 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -32,7 +32,7 @@ ## Feature submission evidence -When startup scripts precede a chosen script, its source must compile before startup scripts run. Invalid chosen source is rejected before startup scripts execute in synchronous and sliced sessions. The chosen script runs the source read before startup scripts, including when a startup script removes its installed file. `crates/engine/tests/script_startup.rs` covers both modes. +When startup scripts precede a chosen script, its source must compile before startup scripts run. Invalid chosen source is rejected before startup scripts execute in synchronous and sliced sessions, and a compilation failure clears the previous script report. The chosen script runs the source read before startup scripts, including when a startup script removes its installed file. Included files are read again when the chosen run starts. Each app queue pump processes at most one startup entry and preserves the remaining order after a failure. `crates/engine/tests/script_startup.rs` covers both modes. History panel row context menus (2026-11-20, G12): Right-clicking any state offers New Document from State, Step to This State, and Clear History. Creating a document uses the clicked snapshot without stepping the source document; Step to This State uses undo/redo and is disabled on the current row; Clear History removes undo and redo steps without changing artwork and is disabled when history is empty. Headless tests in `crates/ui-egui/src/panels/history.rs` cover opening an earlier row menu, snapshot creation, backward/forward jumps, and clearing history. The snapshot chosen when the menu opens is retained while it stays open; pending tool edits are settled before resolving that snapshot to its new row; a discarded snapshot reports that it is unavailable instead of acting on a neighboring row. Jumps settle pending typing before counting undo/redo steps. Shift+F10 opens the focused row menu; Escape dismisses it and restores row focus. Switching documents dismisses the menu before it can act on another document. Headless tests cover these keyboard and document-switch paths. The list and menu use shared Craft UI controls. Scores and estimates unchanged. From 3b029f3fecd76c3a43026970dbbff158c0c2a4b7 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 26 Nov 2026 10:38:39 -0800 Subject: [PATCH 133/151] Keep Anchor Inspector actions reachable in short panels --- crates/ui-egui/src/addons/pathtools.rs | 8 ++++-- crates/ui-egui/src/addons/pathtools/tests.rs | 26 ++++++++++++++++++++ 2 files changed, 32 insertions(+), 2 deletions(-) diff --git a/crates/ui-egui/src/addons/pathtools.rs b/crates/ui-egui/src/addons/pathtools.rs index 1914b37a36..8ad60b5fb4 100644 --- a/crates/ui-egui/src/addons/pathtools.rs +++ b/crates/ui-egui/src/addons/pathtools.rs @@ -17,10 +17,10 @@ pub mod tangent_circle; use craft::behavior::ColumnWidth; use craft::menu::Node; use craft::ui::buttons::Button; -use craft::ui::contract::{Bind, Props as _, Show as _, ShowContainer as _, Sizing, clicked}; +use craft::ui::contract::{Bind, Props as _, Scroll, Show as _, ShowContainer as _, Sizing, clicked}; use craft::ui::display::{Divider, Text}; use craft::ui::form::Field; -use craft::ui::layout_components::{Grid, Row}; +use craft::ui::layout_components::{Grid, Row, Stack}; use craft::ui::patterns::form_dialogs::{DialogFields, FieldValue, HostedParamDialog, Param, ParamDialog, ParamKind}; use craft::ui::runtime::env::{Label, LengthUnits, UnitKind}; use craft::ui::text::NumberField; @@ -192,6 +192,10 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { empty_state(ui, "dc-anchor-smooth", tl!("No document"), tl!("Open a document to edit its anchor points.")); return; } + Stack::new().label(tl!("Anchor Inspector")).fill().scroll(Scroll::vertical()).show(ui, |ui, _| show_inspector(app, ui)); +} + +fn show_inspector(app: &mut VectorcraftApp, ui: &mut Ui) { let readout = readout(app); let anchor = readout.anchor.as_ref(); let selected = app.session.active().is_some_and(|st| !st.selection.is_empty()); diff --git a/crates/ui-egui/src/addons/pathtools/tests.rs b/crates/ui-egui/src/addons/pathtools/tests.rs index df2571a136..9a63194c34 100644 --- a/crates/ui-egui/src/addons/pathtools/tests.rs +++ b/crates/ui-egui/src/addons/pathtools/tests.rs @@ -44,6 +44,32 @@ fn the_inspector_shows_the_selected_anchor_and_its_buttons_edit() { assert!(a.lengths.iter().all(|l| *l > 0.0) && a.angles.iter().all(|d| d.is_some()), "{:?} {:?}", a.lengths, a.angles); } +#[test] +fn a_short_anchor_inspector_scrolls_to_the_selected_anchors_actions() { + let mut app = app(); + let path = app.run("path.create", json!({ "anchors": [{"x": 10, "y": 10}, {"x": 110, "y": 10}, {"x": 110, "y": 110}] })).unwrap(); + let id = vectorcraft_doc::NodeId(path["id"].as_u64().unwrap()); + app.session + .select(|_, sel| { + sel.set([id]); + sel.anchors.insert(id, [(0, 1)].into_iter().collect()); + }) + .unwrap(); + let mut panel = Panel::new(app, super::show); + let room = egui::vec2(220.0, 215.0); + panel.room(room).frame(); + panel.frame(); + let action = "Remove Points, Keep Shape"; + assert!(panel.rect(action).bottom() > room.y, "the action starts clipped"); + panel.focus(action); + let rect = panel.rect(action); + assert!(panel.focused(action) && rect.top() >= 0.0 && rect.bottom() <= room.y, "focus reveals the action: {rect:?}"); + panel.focus("Make Smooth"); + panel.click("Make Smooth"); + let anchor = readout(&panel.app()).anchor.unwrap(); + assert!(anchor.lengths.iter().all(|length| *length > 0.0)); +} + /// Runs `f` on the held options dialog, `None` when none is open. fn held(app: &VectorcraftApp, f: impl FnOnce(Option<&mut HostedParamDialog>) -> R) -> R { app.dialogs().expect("the window's dialogs").with(|h| f(h.get_mut::())) From 90c9b981bbd5640a516a150edfed753ad852b496 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 26 Nov 2026 11:17:44 -0800 Subject: [PATCH 134/151] Qualify the color crate SHA-256 lock dependency --- Cargo.lock | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Cargo.lock b/Cargo.lock index 653aa64e73..905d33b8fc 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -8480,7 +8480,7 @@ dependencies = [ "proptest", "serde", "serde_json", - "sha2", + "sha2 0.10.9", "thiserror 2.0.21", ] From 7e9deb0fb57e64bc0c1d3486fb5a20f624704279 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 26 Nov 2026 11:27:35 -0800 Subject: [PATCH 135/151] Report pending chosen scripts as queued --- crates/ui-egui/src/script_runs.rs | 4 ++-- crates/ui-egui/src/tests/scripts_menu.rs | 4 +++- 2 files changed, 5 insertions(+), 3 deletions(-) diff --git a/crates/ui-egui/src/script_runs.rs b/crates/ui-egui/src/script_runs.rs index 1a17eb6974..11d6c7e599 100644 --- a/crates/ui-egui/src/script_runs.rs +++ b/crates/ui-egui/src/script_runs.rs @@ -130,7 +130,7 @@ fn ask(app: &mut VectorcraftApp) -> bool { /// a folder that is there and cannot be read show in the status bar ([`reply_notes`]). /// → `script.run`'s reply, with `startup` holding `script.startup.run`'s when the startup scripts /// were run: the chosen script's own reply when it ran to its end at once, `{running: true, name}` -/// when it is running, or `{running: true, queued: true}` while a startup script runs before it. +/// when it is running, or `{running: true, queued: true}` while the chosen script waits to start. /// A chosen script that could not start gives its error, as `script.run` does. pub(crate) fn run_chosen(app: &mut VectorcraftApp, params: Value) -> Result { if app.session.startup_skip().is_some() { @@ -146,7 +146,7 @@ pub(crate) fn run_chosen(app: &mut VectorcraftApp, params: Value) -> Result json!({"running": true, "queued": true}), + None if app.session.startup_script_running() || app.session.script_name().is_none() => json!({"running": true, "queued": true}), None => json!({"running": true, "name": app.session.script_name().unwrap_or_default()}), }; if let Some(o) = reply.as_object_mut() { diff --git a/crates/ui-egui/src/tests/scripts_menu.rs b/crates/ui-egui/src/tests/scripts_menu.rs index 0683a1fe6b..300e0dbb32 100644 --- a/crates/ui-egui/src/tests/scripts_menu.rs +++ b/crates/ui-egui/src/tests/scripts_menu.rs @@ -632,7 +632,9 @@ fn a_menu_run_after_a_first_startup_script_that_cannot_start_shows_it_and_runs_t app.session.prefs.show_external_script_warning = false; app.run("prefs.set", json!({"key": "runStartupScripts", "value": true})).unwrap(); app.status("before"); - menus::run_ui_command(&mut app, "ui.runScript", &json!({ "source": DRAW, "name": "chosen" })).unwrap().unwrap(); + let reply = menus::run_ui_command(&mut app, "ui.runScript", &json!({ "source": DRAW, "name": "chosen" })).unwrap().unwrap(); + assert_eq!(reply["running"], true, "{reply}"); + assert_eq!(reply["queued"], true, "{reply}"); let shown = format!("0.jsx: {}", vectorcraft_engine::cmd::scripts::TOO_LARGE); assert_eq!(app.ui.status, shown); finish(&mut app); From 7124a1ae45b6057da8d8321264d42dd7075a07a0 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 26 Nov 2026 11:40:25 -0800 Subject: [PATCH 136/151] Keep Image Trace actions reachable in compact panels --- crates/ui-egui/src/panels/image_trace.rs | 198 +++++++++++++----- .../ui-egui/src/panels/image_trace/tests.rs | 84 ++++++++ crates/ui-egui/src/tests/panel_harness.rs | 7 + 3 files changed, 240 insertions(+), 49 deletions(-) diff --git a/crates/ui-egui/src/panels/image_trace.rs b/crates/ui-egui/src/panels/image_trace.rs index 0dce28aaa8..afd294a0e5 100644 --- a/crates/ui-egui/src/panels/image_trace.rs +++ b/crates/ui-egui/src/panels/image_trace.rs @@ -14,21 +14,26 @@ use std::sync::Arc; // PLAN: assumed import paths of the framework items below: `craft::ui::primitives::IconId`, // `craft::ui::runtime::commands::{CommandState, CommandStates}`, `craft::ui::menu::PanelRow`, // `craft::ui::patterns::presets::*`, `crate::edits` (widgets-w13) and `crate::chrome::rank` (chrome-w16). -use craft::behavior::IconId; +use craft::behavior::{IconId, Metrics, Proposal, ScrollPos, Sense}; use craft::keymap::CommandRef; use craft::ui::buttons::{Button, IconButton, SplitButton, SplitMenu, ToggleButton}; use craft::ui::choice::Checkbox; -use craft::ui::contract::{Bind, Entry, Props as _, Show as _, ShowContainer as _}; +use craft::ui::contract::{ + Bind, BindMut, Common, Component, Container, ContainerProps, Cx, Entry, Props as _, Role, Scroll, Show as _, ShowContainer as _, Sizing, +}; use craft::ui::display::{Divider, Shade, Text}; use craft::ui::form::{Field, SliderField, SliderFieldLayout}; -use craft::ui::layout_components::Row; +use craft::ui::layout::BodyLayout; +use craft::ui::layout_components::{Row, Stack}; use craft::ui::menu::PanelRow; use craft::ui::patterns::presets::{ NameCheck, NamedPresetEvent, NamedPresetRow, NamedPresetStyle, PickerField, PresetError, PresetPicker, PresetRow, PresetSource, PresetState, }; use craft::ui::pickers::Select; use craft::ui::runtime::commands::{CommandState, CommandStates}; +use craft::ui::runtime::env::Env; use craft::ui::sections::Section; +use craft::ui::style::{ComponentStyle, StyleCx}; use egui::Ui; use serde_json::{Value, json}; use vectorcraft_doc::{Node, NodeId, NodeKind, TraceView}; @@ -786,7 +791,6 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { st.preset = "Default".into(); st.params = list.presets.first().map(|p| p.1.clone()).unwrap_or_default(); } - let (is_trace, is_image, any_trace) = (t.is_trace, t.is_image, t.any_trace); // The saved preset changes since the last frame apply to the panel's settings before the selected object's // settings, which `sync_with_object` resolves against every change, are adopted. follow_preset_changes(app, &mut st, &list.presets); @@ -794,6 +798,135 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { let changes: Vec<&TracePresetChange> = app.session.trace_preset_changes_since(0).collect(); sync_with_object(&mut st, t.stored.clone(), t.object, &list.presets, &changes) }; + let preview = app.ui.image_trace_preview; + let mut actions = (false, false, false); + let stack = Stack::new().label(tl!("Image Trace")).fill().scroll(Scroll::vertical()); + let env = Env::of(ui); + let settings_row = env.tokens.size.control.md + env.tokens.space.gap.row; + let footer = Stack::new().id_salt("trace-footer-measure").measure_in(ui, Proposal::Width(ui.available_width()), |ui, _| { + show_footer(ui, preview, &t); + }); + let compact_offset = ui.scope_id().with("trace-compact-offset"); + let settings = if ui.available_height() >= footer.y + settings_row { + if !ui.is_sizing_pass() { + ui.ctx().data_mut(|data| data.remove::(compact_offset)); + } + stack.footer(|ui, _| actions = show_footer(ui, preview, &t)).show(ui, |ui, _| show_settings(app, ui, &mut st, &list, &t)) + } else { + // When the footer moves into the scroll area, start with its actions in view. + let before = ui.ctx().data(|data| data.get_temp(compact_offset)).unwrap_or_default(); + let mut offset = before; + let shown = CompactSettings::new(Bind::bound(&mut offset)).show(ui, |ui, _| { + actions = show_actions(ui, preview, &t); + Divider::horizontal().show(ui); + show_settings(app, ui, &mut st, &list, &t) + }); + if offset != before && !ui.is_sizing_pass() { + ui.ctx().data_mut(|data| data.insert_temp(compact_offset, offset)); + } + shown + }; + let (mut retrace, held) = settings.inner.unwrap_or_default(); + let (preview_toggled, trace_clicked, expand_clicked) = actions; + if !ui.is_sizing_pass() { + hold_source(app, t.any_trace && held); + } + if preview_toggled { + run_reporting(app, "imageTrace.preview", json!({})); + } + if trace_clicked { + trace(app, &mut st); + } + if expand_clicked { + run_reporting(app, "imageTrace.expand", json!({})); + } + // Preview turned on (the checkbox, `imageTrace.preview` or `ui.set`): the selected object is + // traced with the settings that waited in the panel. With no Image Trace object selected, it is + // traced when it is selected again. An object whose settings waited while another object was + // selected is traced when it is selected again with Preview on. + let preview = app.ui.image_trace_preview; + retrace |= preview && (st.preview_off || restored) && t.is_trace && st.params != st.synced["params"]; + if t.is_trace || !preview { + st.preview_off = !preview; + } + cancel_disabled_ignore_sampler(app, &st.params); + if retrace && t.is_trace && preview { + trace(app, &mut st); + } + app.ui.image_trace_panel.shown = st; +} + +/// The very short layout needs a bound offset so returning to it shows the actions first. +#[derive(craft::ui::contract::Component, craft::ui::contract::Props)] +#[component(container, unregistered)] +struct CompactSettings<'a> { + #[common] + common: Common, + #[container] + props: ContainerProps, + offset: Bind<'a, ScrollPos>, +} + +impl<'a> CompactSettings<'a> { + fn new(offset: Bind<'a, ScrollPos>) -> Self { + let props = ContainerProps::new().sizing(Sizing::Fill).layout(BodyLayout::stack()).scroll(Scroll::vertical()); + Self { common: Common::new(), props, offset }.label(tl!("Image Trace")) + } +} + +#[derive(Clone, Debug, PartialEq, ComponentStyle)] +struct CompactSettingsStyle { + #[style(metrics)] + metrics: Metrics, +} + +impl Component for CompactSettings<'_> { + const ROLE: Role = Role::GROUP; + type Style = CompactSettingsStyle; + type Output = egui::Response; + + fn style(_: &StyleCx<'_>, _: CompactSettingsStyleKey) -> CompactSettingsStyle { + CompactSettingsStyle { metrics: Metrics::new() } + } + + fn sense(&self) -> Sense { + Sense::empty() + } + + fn scroll(&mut self) -> Option> { + Some(self.offset.reborrow()) + } + + fn finish(self, cx: Cx<'_, Self>) -> egui::Response { + cx.response.clone() + } +} + +impl Container for CompactSettings<'_> {} + +fn show_footer(ui: &mut Ui, preview: bool, target: &Target) -> (bool, bool, bool) { + Divider::horizontal().show(ui); + show_actions(ui, preview, target) +} + +fn show_actions(ui: &mut Ui, preview: bool, target: &Target) -> (bool, bool, bool) { + let mut value = preview; + let mut trace_clicked = false; + let mut expand_clicked = false; + Row::new().wrap(true).show(ui, |ui, _| { + Checkbox::new(Bind::bound(&mut value)).label(tl!("Preview")).show(ui); + let can_trace = target.is_trace || target.is_image; + let mut trace_button = Button::new(tl!("Trace")).enabled(can_trace); + if !can_trace { + trace_button = trace_button.tooltip(tl!("Select an image to trace")); + } + trace_clicked = trace_button.show(ui).clicked(); + expand_clicked = Button::new(tl!("Expand")).enabled(target.any_trace).show(ui).clicked(); + }); + (value != preview, trace_clicked, expand_clicked) +} + +fn show_settings(app: &mut VectorcraftApp, ui: &mut Ui, st: &mut TraceUi, list: &PresetList, t: &Target) -> (bool, bool) { let mut retrace = false; // A preset button chooses its preset as the Preset row does; the button of the panel's @@ -804,7 +937,7 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { let mut on = was; ToggleButton::new(label, Bind::bound(&mut on)).tooltip(preset_label(name)).show(ui); if on && !was { - retrace |= choose_preset(&mut st, &list.presets, name); + retrace |= choose_preset(st, &list.presets, name); } } }); @@ -824,7 +957,7 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { .show(ui); for event in preset_row.events { match event { - NamedPresetEvent::Apply(name) => retrace |= choose_preset(&mut st, &list.presets, &name), + NamedPresetEvent::Apply(name) => retrace |= choose_preset(st, &list.presets, &name), NamedPresetEvent::Create { name, .. } => run_reporting(app, "imageTrace.presets.save", json!({ "name": name, "params": st.params })), NamedPresetEvent::Rename { key, text, .. } => run_reporting(app, "imageTrace.presets.save", json!({ "name": key, "newName": text })), NamedPresetEvent::Delete(name) => run_reporting(app, "imageTrace.presets.delete", json!({ "name": name })), @@ -845,21 +978,25 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { Row::new().show(ui, |ui, _| { picked = view_pick(ui, st.view); let tip = tl!("Press and hold to view the source image"); - held = - IconButton::new(IconId::new("eye")).label(tip).tooltip(tip).selected(app.ui.trace_hold_source.is_some()).enabled(any_trace).show(ui).held; + held = IconButton::new(IconId::new("eye")) + .label(tip) + .tooltip(tip) + .selected(app.ui.trace_hold_source.is_some()) + .enabled(t.any_trace) + .show(ui) + .held; }); if let Some(v) = picked { st.view = v; - if any_trace { + if t.any_trace { set_view(app, v); } } - hold_source(app, any_trace && held); split_row(app, ui); let data = RowsData::of(app); let main = rows::main_rows(ui, &mut st.params, &data, RowsHost::Panel); - let sampler = Sampler { enabled: is_trace || is_image, armed: app.ui.trace_ignore_sampler.is_some() }; + let sampler = Sampler { enabled: t.is_trace || t.is_image, armed: app.ui.trace_ignore_sampler.is_some() }; let advanced = Section::new(tl!("Advanced")) .open(Bind::bound(&mut app.ui.image_trace_advanced)) .show(ui, |ui, _| rows::advanced_rows(ui, &mut st.params, &data, RowsHost::Panel, Some(sampler))) @@ -880,7 +1017,6 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { cancel_ignore_sampler(app, true); } - Divider::horizontal().show(ui); if let Some((p, a, c)) = st.info { Text::new(crate::i18n::fmt( tl!("Paths: {paths} Anchors: {anchors} Colors: {colors}"), @@ -889,43 +1025,7 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { .shade(Shade::Muted) .show(ui); } - let (mut preview_toggled, mut trace_clicked, mut expand_clicked) = (false, false, false); - Row::new().show(ui, |ui, _| { - let preview = app.ui.image_trace_preview; - let mut value = preview; - Checkbox::new(Bind::bound(&mut value)).label(tl!("Preview")).show(ui); - preview_toggled = value != preview; - let can_trace = is_trace || is_image; - let mut trace_button = Button::new(tl!("Trace")).enabled(can_trace); - if !can_trace { - trace_button = trace_button.tooltip(tl!("Select an image to trace")); - } - trace_clicked = trace_button.show(ui).clicked(); - expand_clicked = Button::new(tl!("Expand")).enabled(any_trace).show(ui).clicked(); - }); - if preview_toggled { - run_reporting(app, "imageTrace.preview", json!({})); - } - if trace_clicked { - trace(app, &mut st); - } - if expand_clicked { - run_reporting(app, "imageTrace.expand", json!({})); - } - // Preview turned on (the checkbox, `imageTrace.preview` or `ui.set`): the selected object is - // traced with the settings that waited in the panel. With no Image Trace object selected, it is - // traced when it is selected again. An object whose settings waited while another object was - // selected is traced when it is selected again with Preview on. - let preview = app.ui.image_trace_preview; - retrace |= preview && (st.preview_off || restored) && is_trace && st.params != st.synced["params"]; - if is_trace || !preview { - st.preview_off = !preview; - } - cancel_disabled_ignore_sampler(app, &st.params); - if retrace && is_trace && preview { - trace(app, &mut st); - } - app.ui.image_trace_panel.shown = st; + (retrace, held) } /// The panel menu's rows: Release and Expand act on the selected Image Trace objects. diff --git a/crates/ui-egui/src/panels/image_trace/tests.rs b/crates/ui-egui/src/panels/image_trace/tests.rs index b72c13639d..3935cbe8c2 100644 --- a/crates/ui-egui/src/panels/image_trace/tests.rs +++ b/crates/ui-egui/src/panels/image_trace/tests.rs @@ -99,6 +99,90 @@ fn traced_app_with_ink(ink: u8) -> VectorcraftApp { app } +fn scroll_settings(panel: &mut Panel, dy: f32) { + panel.scroll_at(egui::pos2(30.0, 30.0), dy); + panel.advance(1.0); + panel.frame(); +} + +#[test] +fn preview_trace_and_expand_stay_reachable_in_a_compact_panel() { + let mut app = traced_app(); + app.run("imageTrace.release", json!({})).unwrap(); + app.ui.image_trace_advanced = true; + let source = first_selected(&app).unwrap(); + assert!(matches!(source.kind, NodeKind::Image(_))); + let mut panel = panel_over(app); + assert!(panel.rect_role("Image Trace", craft::ui::contract::Role::GROUP).is_positive()); + for size in [egui::vec2(148.0, 480.0), egui::vec2(240.0, 170.0), egui::vec2(148.0, 170.0)] { + panel.room(size); + panel.frame(); + panel.frame(); + let room = egui::Rect::from_min_size(egui::Pos2::ZERO, size); + for label in ["Preview", "Trace", "Expand"] { + assert!(panel.in_view(label), "{label} is clipped at {size:?}"); + let rect = panel.rect(label); + assert!(room.contains_rect(rect), "the whole {label} control {rect:?} fits at {size:?}"); + } + assert!(panel.enabled("Trace")); + assert!(!panel.enabled("Expand")); + } + let preview = panel.app().ui.image_trace_preview; + panel.click("Preview"); + assert_ne!(panel.app().ui.image_trace_preview, preview); + + let action = panel.rect("Trace"); + let first_preset = panel.rect("Auto Color").top(); + scroll_settings(&mut panel, -1000.0); + assert!(!panel.shows("Auto Color") || panel.rect("Auto Color").top() < first_preset, "the settings scroll"); + assert_eq!(panel.rect("Trace"), action, "scrolling settings leaves the action in place"); + let ignore = shown(&panel).params["ignoreWhite"].clone(); + panel.click("Ignore Color"); + assert_ne!(shown(&panel).params["ignoreWhite"], ignore, "scrolling reaches the end of Advanced"); + + panel.click("Trace"); + assert!(selected_trace(&panel.app()).is_some()); + assert!(panel.enabled("Expand")); + panel.click("Expand"); + assert!(selected_trace(&panel.app()).is_none()); + assert!(!is_trace(&first_selected(&panel.app()).unwrap())); + panel.app().run("edit.undo", json!({})).unwrap(); + assert!(selected_trace(&panel.app()).is_some()); + + // A single action row needs less height than the wrapped footer in the narrow panel. + panel.room(egui::vec2(240.0, 100.0)); + panel.frame(); + panel.frame(); + scroll_settings(&mut panel, 1000.0); + let action = panel.rect("Trace"); + let first_preset = panel.rect("Auto Color").top(); + scroll_settings(&mut panel, -1000.0); + assert!(!panel.shows("Auto Color") || panel.rect("Auto Color").top() < first_preset, "the short settings viewport scrolls"); + assert!(panel.in_view("Trace")); + assert_eq!(panel.rect("Trace"), action, "a short panel still pins the footer when the actions fit on one line"); + + // Shorten the panel while the settings-only body remains scrolled to Advanced. + panel.room(egui::vec2(148.0, 68.0)); + panel.frame(); + panel.frame(); + let preview = panel.app().ui.image_trace_preview; + panel.click("Preview"); + assert_ne!(panel.app().ui.image_trace_preview, preview, "Preview starts in view in a very short panel"); + let ignore = shown(&panel).params["ignoreWhite"].clone(); + scroll_settings(&mut panel, -1000.0); + panel.click("Ignore Color"); + assert_ne!(shown(&panel).params["ignoreWhite"], ignore, "a very short panel still scrolls to the last setting"); + + panel.room(egui::vec2(240.0, 100.0)); + panel.frame(); + panel.room(egui::vec2(148.0, 68.0)); + panel.frame(); + panel.frame(); + let preview = panel.app().ui.image_trace_preview; + panel.click("Preview"); + assert_ne!(panel.app().ui.image_trace_preview, preview, "shrinking a second time starts at the actions"); +} + #[test] fn sketch_quick_trace_reveals_all_adjustments_and_keeps_the_source() { let mut app = traced_app(); diff --git a/crates/ui-egui/src/tests/panel_harness.rs b/crates/ui-egui/src/tests/panel_harness.rs index 725305d6b3..f9910b0bf8 100644 --- a/crates/ui-egui/src/tests/panel_harness.rs +++ b/crates/ui-egui/src/tests/panel_harness.rs @@ -223,6 +223,13 @@ impl Panel { self.after(); } + /// Turns the wheel by `dy` points over `at`. + pub(crate) fn scroll_at(&mut self, at: Pos2, dy: f32) { + self.frame_with(vec![Event::PointerMoved(at)]); + self.frame_with(vec![craft::ui::testing::pointer::wheel(dy)]); + self.after(); + } + /// Drags from the control named `from` to the one named `to`. pub(crate) fn drag(&mut self, from: &str, to: &str, mods: Modifiers) { let to = self.find(to).center(); From 98dc8b910363c64284addd6c9c581c5b3ac31f88 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 26 Nov 2026 12:11:59 -0800 Subject: [PATCH 137/151] Give each Magic Wand tolerance field an accessible name --- crates/ui-egui/src/panels/magic_wand.rs | 19 +++++++++++++++++-- crates/ui-egui/src/panels/tests_panel_rows.rs | 10 +++++++++- 2 files changed, 26 insertions(+), 3 deletions(-) diff --git a/crates/ui-egui/src/panels/magic_wand.rs b/crates/ui-egui/src/panels/magic_wand.rs index 7a44811ed0..68a151d5fa 100644 --- a/crates/ui-egui/src/panels/magic_wand.rs +++ b/crates/ui-egui/src/panels/magic_wand.rs @@ -44,8 +44,10 @@ fn row(app: &mut VectorcraftApp, ui: &mut Ui, o: &Value, label: &'static str, fl app.run("magicWand.set", json!({ flag: now })).ok(); } if let Some((key, field)) = tol { - Field::new(tl!("Tolerance:")).id_salt(key).enabled(on).show(ui, |ui, _| { - if let Some(n) = field().enabled(on).show(ui).value().copied().flatten() { + let caption = tl!("Tolerance:"); + Field::new(caption).id_salt(key).enabled(on).show(ui, |ui, _| { + let name = format!("{caption} {label}"); + if let Some(n) = field().label(name).keeps_name(true).enabled(on).show(ui).value().copied().flatten() { app.run("magicWand.set", json!({ key: n })).ok(); } }); @@ -114,6 +116,19 @@ pub(crate) fn run(app: &mut VectorcraftApp, id: &str, _params: &Value) -> Option mod tests { use super::*; + #[test] + fn each_tolerance_field_has_its_own_accessible_name() { + use craft::ui::contract::Role; + use craft::ui::testing::Fixture; + + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + let mut fixture = Fixture::new(move |ui| show(&mut app, ui)); + fixture.settle(); + let names: Vec<_> = fixture.by_role(Role::SPIN_BUTTON).into_iter().filter_map(|field| fixture.tree().name_of(field.node)).collect(); + assert_eq!(names, ["Tolerance: Fill Color", "Tolerance: Stroke Color", "Tolerance: Stroke Weight", "Tolerance: Opacity"]); + assert_eq!(fixture.texts().iter().filter(|run| run.text == "Tolerance:").count(), 4); + } + #[test] fn color_tolerance_fields_go_to_100_in_a_cmyk_document() { let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); diff --git a/crates/ui-egui/src/panels/tests_panel_rows.rs b/crates/ui-egui/src/panels/tests_panel_rows.rs index e249c1ea95..01ed51a6a6 100644 --- a/crates/ui-egui/src/panels/tests_panel_rows.rs +++ b/crates/ui-egui/src/panels/tests_panel_rows.rs @@ -74,7 +74,15 @@ fn the_document_info_rows_wrap_in_a_narrow_panel_in_german() { #[test] fn the_magic_wand_rows_wrap_in_a_narrow_panel_in_french() { - let past = past_a_narrow_panel("magicWand", "fr", &["Tolerance:"]); + use crate::i18n::{Lang, LangExt as _, tr}; + + let captions = ["Tolerance:"]; + let panel = floated(app_with_rect(), "magicWand", "fr", Place::Floating(PANEL_MIN_WIDTH), &captions); + let prefix = format!("{} ", tr(Lang::from_code("fr").unwrap(), "Tolerance:")); + let fields: Vec<_> = panel.nodes.iter().filter(|(name, _)| name.starts_with(&prefix)).cloned().collect(); + assert_eq!(fields.len(), 4, "{fields:?}"); + let mut past = panel.past_named(&captions); + past.extend(panel.past(fields)); assert!(past.is_empty(), "past the panel: {past:?}"); } From 4925b64fe5192ce4666a5d690e897f2d48360958 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 26 Nov 2026 12:26:55 -0800 Subject: [PATCH 138/151] Flush native save directories on Unix --- crates/format/src/atomic.rs | 135 ++++++++++++++++++++++++++++++++---- crates/format/src/lib.rs | 2 + docs/mcp.md | 9 ++- docs/target-app-parity.md | 2 + 4 files changed, 131 insertions(+), 17 deletions(-) diff --git a/crates/format/src/atomic.rs b/crates/format/src/atomic.rs index e8f3c42b8e..44a9f01369 100644 --- a/crates/format/src/atomic.rs +++ b/crates/format/src/atomic.rs @@ -1,5 +1,7 @@ -//! Safe saving: a file is written to a temporary file beside it, then renamed over it, so a failed -//! or interrupted write never leaves a damaged file behind (the old one stays as it was). +//! [`write_atomic_with`] writes and flushes a temporary file, then renames it over its destination. +//! A failure while writing or flushing the temporary file leaves the original file unchanged. +//! On Unix, saves also flush the destination directory after the complete file is written. +//! An error at that step reports that the file was written. //! [`write_new_with`] creates a file the same way without ever replacing one. //! //! Where a folder refuses the temporary file or the rename (some network shares, a file another @@ -22,11 +24,29 @@ use std::io::{self, Write as _}; use std::path::{Path, PathBuf}; use std::sync::atomic::{AtomicU64, Ordering}; -/// Whether the returned write error refuses this location. Recovery errors must still be shown: -/// their message names copies the user may need, even when their kind is PermissionDenied. +/// Reports whether a write error identifies a read-only location. +/// It returns false for recovery errors and for errors flushing a directory after a completed write, including PermissionDenied. pub fn read_only_location(error: &io::Error) -> bool { matches!(error.kind(), io::ErrorKind::ReadOnlyFilesystem | io::ErrorKind::PermissionDenied) - && !error.get_ref().is_some_and(|e| e.is::()) + && !error.get_ref().is_some_and(|e| e.is::() || e.is::()) +} + +#[derive(Debug)] +struct WrittenError { + path: PathBuf, + error: io::Error, +} + +impl std::fmt::Display for WrittenError { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + write!(f, "The file was written to {}. Its folder could not be flushed: {}", self.path.display(), self.error) + } +} + +impl std::error::Error for WrittenError { + fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { + Some(&self.error) + } } /// Marks the existing recovery message without changing its text or the returned error kind. @@ -46,11 +66,10 @@ pub fn write_atomic(path: &Path, bytes: &[u8]) -> io::Result<()> { write_atomic_with(path, |f| f.write_all(bytes)) } -/// Write `path` atomically with `fill`, which writes the content into the temporary file. When -/// `fill` or flushing fails, or the work was canceled meanwhile ([`vectorcraft_doc::cancel`]), the -/// temporary file is removed and `path` is left untouched. When the -/// folder refuses the temporary file or the rename, the content is copied into `path` instead (see -/// the module docs). +/// This function writes `path` atomically with `fill`, which writes content into a temporary file. +/// A failure from `fill`, flushing that file, or cancellation ([`vectorcraft_doc::cancel`]) leaves `path` unchanged. +/// Cleanup attempts to remove the temporary file and ignores removal errors. +/// When the folder refuses the temporary file or the rename, the content is copied into `path` instead (see the module docs). pub fn write_atomic_with(path: &Path, fill: impl FnOnce(&mut File) -> io::Result<()>) -> io::Result<()> { // Replacing a file: its staging copy starts owner-only, so a private document is never readable // beside the target before `keep_permissions` has run (#1712). A new file keeps the default mode. @@ -97,7 +116,7 @@ fn write_atomic_stepping( // Best effort: a volume without Unix permissions (SMB, FAT) refuses them, and has none // to keep. let _ = keep_permissions(&target, &tmp); - let Err(e) = rename(&tmp, &target) else { return Ok(()) }; + let Err(e) = rename(&tmp, &target) else { return sync_written_parent(&target) }; e } }; @@ -137,7 +156,7 @@ fn write_over(tmp: &Path, target: &Path, refused: io::Error) -> io::Result<()> { if let Some(old) = old { let _ = std::fs::remove_file(old); } - Ok(()) + sync_written_parent(target) } (Err(e), Some(old)) => Err(io::Error::new( e.kind(), @@ -168,7 +187,7 @@ fn create_private(path: &Path) -> io::Result { /// (`std::fs::hard_link`, which fails with `AlreadyExists` when the name is taken, also when it was /// taken meanwhile). The file appears whole or not at all. Where hard links fail for another /// reason, `path` is created with `create_new` and the content copied in; a failed copy removes -/// it. The temporary file is always removed. +/// it. Cleanup attempts to remove the temporary file and ignores removal errors. pub fn write_new_with(path: &Path, fill: impl FnOnce(&mut File) -> io::Result<()>) -> io::Result<()> { write_new_linking(path, fill, |tmp, path| std::fs::hard_link(tmp, path)) } @@ -189,7 +208,31 @@ fn write_new_linking( }); // Best effort: the temporary file is all there is to clean up. let _ = std::fs::remove_file(&tmp); - placed + placed.and_then(|()| sync_written_parent(path)) +} + +fn sync_written_parent(path: &Path) -> io::Result<()> { + #[cfg(unix)] + { + sync_parent(path).map_err(|error| io::Error::new(error.kind(), WrittenError { path: path.to_path_buf(), error })) + } + #[cfg(not(unix))] + { + let _ = path; + Ok(()) + } +} + +/// This function flushes the directory containing `path` with `fsync`. +/// It returns errors from opening or flushing the directory. +#[cfg(unix)] +pub fn sync_parent(path: &Path) -> io::Result<()> { + #[cfg(test)] + if DIRECTORY_SYNC_FAILS.with(std::cell::Cell::get) { + return Err(io::Error::new(io::ErrorKind::PermissionDenied, "directory flush failed")); + } + let parent = path.parent().filter(|parent| !parent.as_os_str().is_empty()).unwrap_or_else(|| Path::new(".")); + rustix::fs::fsync(&File::open(parent)?).map_err(io::Error::from) } /// `Err` wrapping [`vectorcraft_doc::cancel::Cancelled`] when the work running on this thread has @@ -272,6 +315,8 @@ const ENOTTY: i32 = 25; #[cfg(test)] thread_local! { + #[cfg(unix)] + static DIRECTORY_SYNC_FAILS: std::cell::Cell = const { std::cell::Cell::new(false) }; /// Tests: every full flush on this thread fails as on an SMB share mounted by macOS. static REFUSE_FULL_SYNC: std::cell::Cell = const { std::cell::Cell::new(false) }; /// Tests: the plain `fsync` fallback fails too, with this OS error. @@ -472,6 +517,68 @@ mod tests { let _ = std::fs::remove_dir_all(&d); } + #[cfg(unix)] + #[test] + fn a_directory_sync_failure_reports_the_completed_replacement() { + let directory = vectorcraft_testkit::TempDir::new("atomic-directory-sync-replace"); + let path = directory.join("doc.vectorcraft"); + std::fs::write(&path, b"old").unwrap(); + DIRECTORY_SYNC_FAILS.with(|flag| flag.set(true)); + let result = write_atomic(&path, b"new"); + DIRECTORY_SYNC_FAILS.with(|flag| flag.set(false)); + assert!(result.is_err(), "a failed directory flush was reported as success"); + let error = result.unwrap_err(); + assert_eq!(error.kind(), io::ErrorKind::PermissionDenied); + assert!(error.to_string().contains("The file was written to"), "{error}"); + assert!(!read_only_location(&error), "the file was already replaced: {error}"); + assert_eq!(std::fs::read(&path).unwrap(), b"new"); + assert!(leftovers(&directory, "doc.vectorcraft").is_empty()); + write_atomic(&path, b"retried").unwrap(); + assert_eq!(std::fs::read(&path).unwrap(), b"retried"); + } + + #[cfg(unix)] + #[test] + fn a_directory_sync_failure_preserves_the_completed_new_file() { + let directory = vectorcraft_testkit::TempDir::new("atomic-directory-sync-create"); + let path = directory.join("doc.vectorcraft"); + DIRECTORY_SYNC_FAILS.with(|flag| flag.set(true)); + let result = write_new_with(&path, |file| file.write_all(b"created")); + DIRECTORY_SYNC_FAILS.with(|flag| flag.set(false)); + assert!(result.is_err(), "a failed directory flush was reported as success"); + let error = result.unwrap_err(); + assert_eq!(error.kind(), io::ErrorKind::PermissionDenied); + assert!(error.to_string().contains("The file was written to"), "{error}"); + assert!(!read_only_location(&error), "the file was already created: {error}"); + assert_eq!(std::fs::read(&path).unwrap(), b"created"); + assert!(leftovers(&directory, "doc.vectorcraft").is_empty()); + let result = write_new_with(&path, |file| file.write_all(b"replacement")); + assert_eq!(result.unwrap_err().kind(), io::ErrorKind::AlreadyExists); + assert_eq!(std::fs::read(&path).unwrap(), b"created"); + } + + #[cfg(unix)] + #[test] + fn a_directory_sync_failure_is_reported_after_copy_fallbacks() { + let directory = vectorcraft_testkit::TempDir::new("atomic-directory-sync-copy"); + let path = directory.join("doc.vectorcraft"); + std::fs::write(&path, b"old").unwrap(); + DIRECTORY_SYNC_FAILS.with(|flag| flag.set(true)); + let replaced = write_atomic_stepping(&path, |file| file.write_all(b"new"), create_new, |_, _| denied()); + DIRECTORY_SYNC_FAILS.with(|flag| flag.set(false)); + let error = replaced.unwrap_err(); + assert!(!read_only_location(&error), "the file was already replaced: {error}"); + assert_eq!(std::fs::read(&path).unwrap(), b"new"); + let new_path = directory.join("new.vectorcraft"); + DIRECTORY_SYNC_FAILS.with(|flag| flag.set(true)); + let created = write_new_linking(&new_path, |file| file.write_all(b"created"), |_, _| denied()); + DIRECTORY_SYNC_FAILS.with(|flag| flag.set(false)); + let error = created.unwrap_err(); + assert!(!read_only_location(&error), "the file was already created: {error}"); + assert_eq!(std::fs::read(&new_path).unwrap(), b"created"); + assert_eq!(std::fs::read_dir(&*directory).unwrap().count(), 2); + } + /// A save to an SMB share (#1620): macOS refuses the full flush there with `ENOTSUP`, so the /// file is flushed with a plain `fsync` and saved. When that fails too the save fails as before, /// the old file stays and no temporary file is left. Elsewhere `sync_all` is already a plain diff --git a/crates/format/src/lib.rs b/crates/format/src/lib.rs index 66040d265c..0c09df22d1 100644 --- a/crates/format/src/lib.rs +++ b/crates/format/src/lib.rs @@ -55,6 +55,8 @@ use serde::{Deserializer, Serialize}; use vectorcraft_brush::stored_art::StoredArt; use vectorcraft_doc::{Document, ImageBlob}; +#[cfg(all(unix, not(target_arch = "wasm32")))] +pub use atomic::sync_parent; #[cfg(not(target_arch = "wasm32"))] pub use atomic::{read_only_location, sync_file, write_atomic, write_atomic_with, write_new_with}; use craft_gzip::Gz; diff --git a/docs/mcp.md b/docs/mcp.md index a12daa1b46..09b7a62543 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -1393,9 +1393,12 @@ Each coordinate goes to the nearest step of its stored binary value, and a value zero (`0.125` at 2 places is `0.13`); `1.005` is stored as slightly less than that and is written as `1.0`. Each anchor is rounded on its own, so a closed path stays closed and a shape smaller than one step keeps its anchors on one point. Opening the file and saving it again does not bring back the dropped digits. The embedded preview and the PDF that `pdfCompatible: true` adds show the rounded paths. Without `precision` a save writes the coordinates exactly, and Save does not remember it. A `.ai` file ignores -`precision`. A save writes -a temporary file and renames it over the old one, so a failed save never damages the file; only the images the -document uses are written, and document keys written by a newer version are kept. +`precision`. A save first writes and flushes a temporary file, then renames it over the destination or copies the complete +content into the destination. The copy path keeps a flushed copy of any existing content before overwriting it. +A failure during that copy reports the locations of the new content and any saved original. +Only the images the document uses are written, and document keys written by a newer version are kept. +On Unix, a save flushes the destination directory after writing or replacing the file. If that flush fails, +the save reports an error stating that the file was written. An uncompressed file is indented JSON when the document has at most 2,000 layers and objects and the indented document, as the chosen version writes it, is at most 1 MiB; otherwise the file is compact JSON. diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index d56d4fd4cd..3283f694f1 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1,5 +1,7 @@ # Parity with Adobe Illustrator +Native saves on Unix flush the destination directory after writing or replacing a file. If the directory cannot be flushed, the save returns an error stating that the file was written. + > **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-25 · **Change:** minor (Essentials readiness row: Shape Builder item names its remaining depth, #937's fix unconfirmed on the reporter's file, #8314; scores and estimates unchanged; previously: G12: History row context menus use shared Craft controls, snapshot targeting, keyboard access and document-switch dismissal (#8845); scores and estimates unchanged; previously: G12: Document Info Selection Only counts the selection, and with no artwork selected it shows (No artwork selected) and artboards the Artboard tool has selected still show; scores and estimates unchanged; previously: Pencil Edit Selected Paths follows lifted strokes, carves, loops, closes and redraws compound paths; Layers: a targeted item with an appearance of its own keeps its inner ring visible around a smaller appearance dot, so the target circle's four looks differ, #8711; scores and estimates unchanged; previously: G12: Asset Export tile context menus; scores and estimates unchanged; previously: M14/G12: Appearance panel: right-click item context menus for rows (Duplicate, Delete, Hide/Show, Edit Effect, Clear Appearance, Reduce to Basic Appearance) with selection handling, #8809; previously: Text styles panel: right-click item context menus for Character Styles and Paragraph Styles with Options, Duplicate, Delete, Redefine, Clear Overrides; scores and estimates unchanged; previously: G12: Actions panel item context menus for action sets (New Action…, New Set…, Duplicate Set, Delete Set, Set Options…) and actions (Play, Record, Duplicate, Delete, Action Options…, Batch…) with selection handling; clicking Duplicate on an action duplicates that action; headless tests in `crates/ui-egui/src/panels/actions.rs`; scores and estimates unchanged; previously: Layers: a targeted item with an appearance of its own keeps its inner ring visible around a smaller appearance dot, so the target circle's four looks differ, #8711; scores and estimates unchanged; previously: Trim View hides the ruler guides, guide paths and the grid while it is on and greys out Show/Hide Guides and Show/Hide Grid, #8363; scores and estimates unchanged; previously: Scissors shows the actual proposed cut point while hovering, using its existing snapping and cut target (#8655); scores and estimates unchanged; previously: G12: Brushes panel: item right-click context menu (Brush Options, Duplicate Brush, Delete Brush) with selection handling; scores and estimates unchanged; previously: Graphic Styles panel: right-click item context menu for tiles and rows with Options, Duplicate, Delete, Redefine, Break Link; scores and estimates unchanged; previously: In the web build, an edit while the view of a heavy document moves (a tool drag held at an edge of the canvas, #8551, or a wheel scroll during a drag) draws only the part it changed into the last frame, which stays drawn moved with the view, instead of rendering the whole canvas each frame, and edits that go on once the view is still don't put off its render (#8688); scores and estimates unchanged; previously: G12: Links panel row context menu (Relink…, Go To Link, Update Link, Edit Original, Show in Folder, Embed Image / Unembed…) with selection handling; scores and estimates unchanged; previously: Artboard tool: Shift held once a move or Alt-copy drag is under way keeps it to the level, upright or 45° line, #8580; scores and estimates unchanged; previously: Image Trace Ignore Color keeps the canvas View and stays armed on a missed pixel (#8068); a tool drag held near an edge of the canvas scrolls the view, #8551; scores and estimates unchanged; previously: G12: Place: show progress window with Cancel for slow placed files exceeding 0.4 s, part of #5930; scores and estimates unchanged; previously: All Tools drawer: a tool the toolbar holds is dimmed in the readable dim text colour, not the disabled colour that was unreadable against the panel, and a hovered dimmed row takes the panel's darker fill so it stays readable, #8294; scores and estimates unchanged; previously: Layers: selected guide rows stay highlighted after the pointer leaves (#7344); scores and estimates unchanged; previously: PDF import: type filled and stroked after a page of type filled only comes in filled and stroked, #8549 follow-up; scores and estimates unchanged; previously: selected Dimension extension-line color and weight in Properties (#7078; four focused UI regressions passed); scores and estimates unchanged; previously: Brush Options Key Color: restore canvas input for the existing one-shot pick, then resume the retained draft and previous tool (#8284; six full-app input regressions passed); scores and estimates unchanged; previously: #8200: `.ai` and EPS import: an Art brush in Tints of a swatch-linked stroke color comes in brushed, its tints linked to the swatch; scores and estimates unchanged; previously: Ellipse: Up/Down changes Anchors while drawing (#7840); scores and estimates unchanged; previously: Windows/Linux menu access keys and localized cues (#6596); previously: Backquote/~ arrow pattern nudges (#7717); scores and estimates unchanged; previously: Window > Toolbars > Compact Tools offers optional denser main Tools spacing (#7234); default layout, scores and estimates unchanged; previously: Direct Selection: Space during an ordinary path's handle drag repositions its anchor and handles, including a Pen loan (#7237, request 3 only; scores and estimates unchanged); previously: SVG export preserves document units on root width/height for physical units, #864; G11 estimate 8–15 → 6–13 h; previously: Floating panels keep their window level while focus moves between the app's windows, so a press on one panel's bar no longer hands the keyboard to another, #6986; scores and estimates unchanged; previously minor: #8128: `.ai` and EPS import: clipping paths grouped in a compound path are its subpaths, so the compound clipping path clips its clipping group; scores and estimates unchanged; previously: import: type filled and stroked by a `TJ` whose kerning starts a new line comes in filled and stroked, #8543; PDF Retype phase 1 (#4934): Type › Retype (`type.retype`) turns outlined text that exactly matches an available font back into point text; scores and estimates unchanged; previously: Lock Guides: a selection marquee (Selection, Direct Selection, Group Selection, Enclosing Lasso) leaves out paths made into guides inside groups and compound paths too, as clicks do (#3074), so a group is no longer selected by a locked guide in it; an enclosing marquee measures a group without its locked or hidden guides, and Direct Selection takes no anchor or segment of a guide that can't be picked; a guide in a group still moves with its group (#8538); Production Preflight: output-aware fonts, text overflow, linked files and effective image resolution, clickable findings and automatic rechecking; scores and estimates unchanged; previously: PDF export writes the document language as the catalog's `/Lang`, #3644; Layers panel: an Alt-drag copies a row above or below itself, so the top layer dragged up, the bottom layer dragged down and a lone layer are copied, #8237; scores and estimates unchanged; previously: Twist: a strongly twisted path joins its pieces without kinks, #7069; scores and estimates unchanged; previously: PDF import: a glyph filled only after a glyph filled and stroked comes in filled only, not stroked, #8300; PDF import: translucent type filled and stroked comes in as a filled type object and a stroked one, as the file composites them, and an upright glyph is never kept as the outline of its glyph alone, #8015; PDF import: type filled and stroked by one text-showing operator comes in as one type object, filled and stroked, not a stroked copy over a filled one, #8015; Layers panel: Alt over the list shows the copy cursor while rows or the selection square are dragged, #8217; scores and estimates unchanged; previously: Gradient panel: the add-stop strip under the ramp shows the white arrow with a plus on Windows and X11, #8241; scores and estimates unchanged; previously: Properties panel: the Character section shows the font of the Type tool's selection, not the first run's (#8189); scores and estimates unchanged; previously: Recolor Artwork follow-up (#8031, remaining #4028): native Lab input, picker swatch libraries and Assign-row menus; UI interaction regression coverage; scores and estimates unchanged; previously: Eraser review: hidden Rasterize and Along/Across stroke rows do not block preserving visible gradients; scores and estimates unchanged; previously: Eraser review: ordinary Group/Layer paints and reproducible evaluated gradient placements are preserved; other placements retain existing fitting; scores and estimates unchanged; previously: Eraser: shared fill-only area cutting for fixed and varied tips and the Alt-drag marquee, #6582; scores and estimates unchanged; previously: #8005: the Color spectrum fills a resized panel; scores and estimates unchanged; previously: Paragraph composers (#4935): the Paragraph panel menu and paragraph styles offer four composers, the Middle Eastern & South Asian Single-line and Every-line (how all type is set, and the default) and a Standard Single-line and Every-line that set Indic, Arabic and Hebrew type glyph by glyph as the font maps it, for legacy fonts that keep a script on Latin character codes; PDF import: stroked type keeps the line cap, line join and miter limit the file strokes it with, a glyph stroked otherwise than the run it joins coming in as a run of its own, #7741; G5: Neon & Glow joins built-in graphic style libraries (Cyan Neon, Magenta Laser, Amber Tube, Electric Lime, Pulse Violet, Cobalt Phosphor); scores and estimates unchanged; previously: Pencil ignores Smart Guides and Snap to Point and shows no Smart Guides, #7252; previously: Pencil continuation, straight-line and closing cursors; scores and estimates unchanged; previously: G5: Weather Icons joins built-in symbol libraries (Sun, Moon, Cloud, Rain, Thunder, Snow); scores and estimates unchanged; previously: a closed Pencil stroke closes with a straight segment; previously: Snap to Point with Smart Guides off draws no Smart Guides labels or lines, #7250; previously: 3D: the seams of Extrude & Bevel, Inflate and Rotate under a white light, and of the faces of Extrude & Bevel (Classic), Revolve (Classic) and Rotate (Classic), went from miter to round joins, so white-light 3D output is expected to differ from the 2026-10-17 comparison at facet corners (not measured: the scenes were not exported again); previously: `.ai` and EPS import: in layers that don't draw as the page, art that differs away from an envelope of type no longer costs it its editable type; it keeps its drawn art where, in the pixels it and its drawn art ink, the layers with it differ from the page more than its own check allows, or past the envelopes' share of the page check, #7141; Character panel: the Set Font Height Reference dropdown shows an icon before each reference, #6304; scores and estimates unchanged; previously: Envelopes: a top object's side columns; scores and estimates unchanged; previously: Graphic Styles list fills a taller panel, #2992; scores and estimates unchanged; previously: PDF import: glyphs in a span with an empty ActualText come in as outlines, #6971; scores and estimates unchanged; previously: library panels' lists fill a taller panel, #2992; scores and estimates unchanged; previously: Swatches list fills a taller panel, #1638; scores and estimates unchanged; previously minor: Object › Rasterize with the Grayscale or Bitmap colour model makes a grayscale image, #6969; scores and estimates unchanged; previously minor: `.ai` and EPS import: type in an envelope with Distort Appearance is also tried mapped from the box of what it paints, miter tips and moved strokes included, after its glyphs grown by half its strokes' weight (#6824; #6617: Swatches panel menu: Show Recent Colors; scores unchanged; previously minor: icon-strip flyouts also resize from the top edge and the canvas-side top corner, keeping the moved top in workspaces (storytold/craft-libs#1094); scores and estimates unchanged; previously: #6865: explicitly requested oversized editing artboard; macOS: the canvas cursor stays after the pointer moves, #6362; scores and estimates unchanged; previously minor: Type tool: kerning at a caret at the start of a line moves the character after it, #5111; scores and estimates unchanged; previously minor: Rulers: the zero point dragged out of the rulers' corner snaps as a drawn point does; previously minor: Live Paint Bucket fills faces crossed in one drag (#6373); previously: #6404: transform-aware Eyedropper character copying; scores and estimates unchanged; previously: Envelopes: with Distort Appearance, type's strokes paint along the bent glyph outlines at their own weight, as users' `.ai` files draw them, which changes how VectorCraft's own envelopes of stroked type draw (#6644; scores and estimates unchanged); previously minor: G5: Energy Beams brush library; bundled content ~44% → ~46%; previously minor: G5: Skill Icons symbol library; bundled content ~42% → ~44%; previously minor: `.ai` and EPS import: an envelope saved in Edit Contents whose mesh lies away from its drawn art by a move opens live on that art (#6570; scores and estimates unchanged); previously minor: ruler double-click adds a guide at the pointer, #5239; G5: Status Effects graphic style library; bundled content ~40% → ~42%; MCP symbol libraries list UI Frames and Map Markers; previously minor: G5: Inventory Icons built-in symbol library; bundled content ~38% → ~40%; previously minor: `.ai` and EPS import: stroked type in an envelope maps from its glyphs grown by half its stroke (#3179; scores and estimates unchanged); previously minor: `.ai` and EPS import: warps of type open as mesh envelopes on their saved grid where VectorCraft's warp doesn't draw as their drawn art (#3179; scores and estimates unchanged); G5: Game Trails brush library; bundled content ~36% → ~38%; previously minor: Edit › Edit Custom Dictionary…: its dialog adds, deletes and changes the custom dictionary's words, #4936; previously minor: `.ai` and EPS import: envelopes of type open live where they draw as their drawn art and the layers with them draw as the page (#3179; scores and estimates unchanged); G5: Game HUD graphic style library; bundled content ~34% → ~36%; previously minor: Line Arrow arrowhead (#5421; scores and estimates unchanged); G5: Map Markers built-in symbol library; bundled content ~32% → ~34%; previously minor: right-click on type: Spelling › Auto Spell Check, with its check mark, #4936; previously minor: right-click on a word Auto Spell Check underlined: its suggestions, Ignore All and Add to Dictionary, #4936; previously minor: Canvas: a 3D effect changed on type or a group redraws where its solid was; Fit to Artwork Bounds and per-artboard SVG export build each solid once for all artboards; previously minor: Effect Gallery: a thumbnail for each filter and a preview area inside the dialog, on an original drawing; Raster effects 52% → 55%, hours 1–2 → none; headline numbers unchanged; Auto Spell Check: `edit.autoSpellCheck` underlines the unknown words, #4936; previously minor: PDF editable import preserves authored ActualText once, including empty/nested spans and authored ordering (#6165); cross-line/style layout remains approximate; scores and estimates unchanged; PDF marked-text export (#6309): compatible glyphs stay on one layout line with per-glyph offsets; scores and estimates unchanged; G5: UI Frames built-in symbol library with default 9-slice; bundled content ~32%; previously minor: G5: dynamic symbol part on-canvas opacity/blend/gradient/pattern; strokes remaining no longer lists Overlap/auto corners; symbols ~88%; previously minor: interim macOS cursor delivery, #2292; native validation pending; scores and estimates unchanged; previously minor: harakat paint fallback clarified; previously minor: current Guides feature-area rows consolidated using existing ruler evidence; scores and estimates unchanged; previously minor: Control bar › Snapping includes the existing Snap to Glyph and Alignment Guides toggles (#6164); scores and estimates unchanged; previously minor: G5 docs: Art brush Overlap and Pattern brush auto corners removed from strokes remaining; symbols remaining lists dynamic on-canvas beyond solid and guides outside the art; previously minor: custom dictionary and Ignore All: `text.spelling.addWord`, `removeWord`, `changeWord`, `dictionary` and `ignoreAll`, #4936; previously minor: EPS import: embedded fonts (composite, Type 42, CID-keyed, Type 1, CFF FontSet) draw their glyphs; spell check engine: `text.spelling.check` and `text.spelling.suggest` on craft-proof, #4936; previously minor: floating tab groups collapse into the side icon rail and opened rail panels fold back into it, #5925 in part; `.ai`/EPS type keeps its tab stops, and right-aligned lines with tabs lay out as the file's page, #6147; `.ai`/EPS type from the text document lays its lines out closer to the file's page, within limits, #6137; `.ai` and EPS import: older Art brush objects read; numeric fields step on wheel hover without taking keyboard focus, and a panel wheel turn cannot seed a canvas zoom glide, #5949; Character Styles panel: a double-click on a style's row opens its Character Style Options; the dialog keeps a fixed width and scrolls its sections, so its buttons stay on screen; Tools stays beside the canvas with left-side panels; new gradients follow document color mode; Selection QoL: marquee modes and visible feedback, #5313; SVG CSS classes survive export and repeated import in all four styling modes (#2480); current-main integration retains event attributes and scripts; #3380 deletion-only review follow-up: independent survivors keep gradient placement, owned subpaths avoid discarded copies, and contracts/status/evidence are clarified; endpoint highlighting remains open; scores and estimates unchanged; the canvas keeps selection outlines and anchors between frames; Indian-language hyphenation review and license allowlist, #4947; Stroke gradients: an arrowhead aligned to the tip is painted to the corners of its base, #5964; Drop Shadow and glow dialogs: spinner arrows, #5367, #5368; Stroke Weight Up and Down shortcuts, #5797; Hindi catalog and contributor loanword preferences; full wording review in progress; Properties in Edit Artboards: a Transform section with the reference point above the Artboards section, #5219; the Control bar's Stroke: and Opacity: links scrub their fields, #4088; an image zoomed in on is separated, colorized or proofed only where it shows (#4155); a document's first frame renders on the render worker, so opening a heavy file no longer freezes the window, #4155; Control bar Paragraph section with type selected, #5372; translating unchanged type reuses its glyph and character-stroke outlines; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x; public release notes through 30.7, August 2026; Units › East Asian Type acts, with Q and Ha units; scores unchanged) > > Tech Circuit update (2026-11-14): three original procedural brushes; ten built-in brush libraries (G5). From e6d5e51f0efbe3a11bba7c434e66cd3b26fb1217 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 26 Nov 2026 12:41:28 -0800 Subject: [PATCH 139/151] Require fresh export confirmation after changing documents --- .../ui-egui/src/dialogs/export_for_screens.rs | 13 +++++--- crates/ui-egui/src/dialogs/tests_screens.rs | 30 +++++++++++++++++++ 2 files changed, 39 insertions(+), 4 deletions(-) diff --git a/crates/ui-egui/src/dialogs/export_for_screens.rs b/crates/ui-egui/src/dialogs/export_for_screens.rs index 5e765e306c..0211830949 100644 --- a/crates/ui-egui/src/dialogs/export_for_screens.rs +++ b/crates/ui-egui/src/dialogs/export_for_screens.rs @@ -996,17 +996,17 @@ pub(crate) fn pump(app: &mut VectorcraftApp, ctx: &Context) { let key = app.session.active().map(|st| (st.uid, st.revision)); let pdf_presets = pdf::presets(&app.session); let saved = &app.session.prefs.screen_export_presets; - let Some((stale, pending, rename, filed)) = dialogs.with(|host| { + let Some((shown, pending, rename, filed)) = dialogs.with(|host| { let d = host.get_mut_by_id::(id)?; screen_formats::preset_list(&mut d.presets, saved); if d.pdf_presets != pdf_presets { d.pdf_presets = pdf_presets; } - Some((d.doc.as_ref().map(|s| s.key) != key, d.pending.take(), d.rename.take(), d.held.take())) + Some((d.doc.as_ref().map(|s| s.key), d.pending.take(), d.rename.take(), d.held.take())) }) else { return; }; - if stale { + if shown != key { let (doc, thumbs) = document_view(app, ctx); dialogs.with(|host| { if let Some(d) = host.get_mut_by_id::(id) { @@ -1031,7 +1031,12 @@ pub(crate) fn pump(app: &mut VectorcraftApp, ctx: &Context) { rename_artboard(app, board, &name); } if let Some(fields) = filed { - let answer = params(app, &fields).and_then(|p| io::export_for_screens(app, p)).map(drop).map_err(Label::from); + // OK validated its selection against the document the dialog showed before refreshing. + let answer = if shown.map(|(uid, _)| uid) == app.session.active().map(|st| st.uid) { + params(app, &fields).and_then(|p| io::export_for_screens(app, p)).map(drop).map_err(Label::from) + } else { + Err(Label::from(tl!("The active document changed. Review the export selection and try again."))) + }; dialogs.with(|host| { if let Some(d) = host.get_mut_by_id::(id) { d.held.answer(answer); diff --git a/crates/ui-egui/src/dialogs/tests_screens.rs b/crates/ui-egui/src/dialogs/tests_screens.rs index 8a73810d89..af68809f46 100644 --- a/crates/ui-egui/src/dialogs/tests_screens.rs +++ b/crates/ui-egui/src/dialogs/tests_screens.rs @@ -67,6 +67,36 @@ fn stays_open(app: &mut VectorcraftApp) { assert_eq!(kind(app).as_deref(), Some(export_for_screens::KIND)); } +#[test] +fn a_queued_export_requires_fresh_confirmation_after_switching_documents() { + use craft::ui::dialog::{HeldOk, dialog_id}; + + let (mut app, log) = app(1, true); + let source = app.session.active().unwrap().uid; + app.run("file.new", json!({"width": 40, "height": 30})).unwrap(); + app.run("artboard.rename", json!({"indices": [0], "name": "Destination"})).unwrap(); + let destination = app.session.active().unwrap().uid; + app.run("window.previousDocument", json!({})).unwrap(); + assert_eq!(app.session.active().unwrap().uid, source); + open(&mut app); + + let ctx = app.ui_ctx.clone().unwrap(); + let dialogs = app.dialogs().unwrap(); + let id = dialog_id(export_for_screens::KIND); + dialogs.with(|host| { + assert!(!host.confirm_by_id(&ctx, id)); + assert_eq!(host.held_state(id), Some(HeldOk::Waiting)); + }); + app.run("window.nextDocument", json!({})).unwrap(); + assert_eq!(app.session.active().unwrap().uid, destination); + export_for_screens::pump(&mut app, &ctx); + + assert!(log.borrow().is_empty(), "the earlier OK cannot download from the destination tab"); + assert!(matches!(dialogs.with(|host| host.held_state(id)), Some(HeldOk::Refused(_)))); + try_confirm(&mut app).unwrap(); + assert_eq!(log.borrow().iter().map(|(name, _)| name.as_str()).collect::>(), ["Destination.png"]); +} + fn temp_folder(tag: &str) -> std::path::PathBuf { std::env::temp_dir().join(format!("vc-efs-{tag}-{}", std::process::id())) } From 735bdc09184520d947c4ca2722b37102abd7657b Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 26 Nov 2026 12:53:14 -0800 Subject: [PATCH 140/151] Preserve custom arrowhead attachment in Stroke previews --- crates/ui-egui/src/panels/stroke.rs | 32 ++++++++++++++++++++++++++--- 1 file changed, 29 insertions(+), 3 deletions(-) diff --git a/crates/ui-egui/src/panels/stroke.rs b/crates/ui-egui/src/panels/stroke.rs index e47111a613..d7406230d7 100644 --- a/crates/ui-egui/src/panels/stroke.rs +++ b/crates/ui-egui/src/panels/stroke.rs @@ -136,7 +136,7 @@ pub(crate) fn builtin_arrow_name(label: &str) -> &str { crate::i18n::tr_ctx(crate::i18n::current(), "arrowhead", label) } -/// The preview cache key of `a`: its name, and for a custom head its art. +/// The preview cache key of `a`: its name, and for a custom head its art and where the stroke ends. fn arrow_key(a: Option<&Arrowhead>) -> String { match a { Some(Arrowhead::Custom(c)) => { @@ -148,6 +148,7 @@ fn arrow_key(a: Option<&Arrowhead>) -> String { (p.x.to_bits(), p.y.to_bits()).hash(&mut h); } } + c.stop().to_bits().hash(&mut h); format!("custom:{}:{:x}", c.name, h.finish()) } _ => format!("{a:?}"), @@ -487,8 +488,13 @@ pub(super) fn arrow_doc(mut a: Option, start: bool, w: f64, h: f64) - let weight = fit(w - 6.0, long).min(fit(h / 2.0 - 1.0, half)).min(2.5); inset = -b.x0.min(0.0) * weight; if weight < LEAST { - let path = c.path.transformed(vectorcraft_geom::Affine::scale(weight / LEAST)); - a = Some(Arrowhead::Custom(std::sync::Arc::new(vectorcraft_doc::CustomArrowhead::new(c.name.clone(), path)))); + let shrink = weight / LEAST; + let path = c.path.transformed(vectorcraft_geom::Affine::scale(shrink)); + let mut head = vectorcraft_doc::CustomArrowhead::new(c.name.clone(), path); + if let Some(stop) = c.stop { + head = head.with_stop(stop * shrink); + } + a = Some(Arrowhead::Custom(std::sync::Arc::new(head))); } scale = scale.min(weight.max(LEAST) / WIDTH * 100.0); } @@ -735,6 +741,26 @@ mod tests { assert!(top.iter().chain(&bottom).all(|p| (p.y - r.center().y).abs() <= 0.35 * (r.height() / 2.0 - 1.0) + 1e-3)); } + #[test] + fn custom_arrowhead_thumbnails_preserve_where_the_stroke_ends() { + use vectorcraft_doc::CustomArrowhead; + use vectorcraft_geom::{PathData, Point, SubPath}; + + let outline = PathData::single(SubPath::polyline(&[Point::new(0.0, -60.0), Point::new(4.0, 60.0), Point::new(4.0, -60.0)], true)); + let custom = CustomArrowhead::new("Wide Flag".into(), outline); + let halfway = Arrowhead::Custom(std::sync::Arc::new(custom.clone())); + let explicit_stop = Arrowhead::Custom(std::sync::Arc::new(custom.with_stop(0.75))); + assert_ne!(arrow_key(Some(&halfway)), arrow_key(Some(&explicit_stop)), "each stroke attachment needs its own thumbnail"); + + let preview = arrow_doc(Some(explicit_stop), true, 56.0, 22.0).unwrap(); + let node = preview.node(preview.selectable_art()[0]).unwrap(); + let Some(Arrowhead::Custom(head)) = &node.appearance.stroke().unwrap().start_arrow else { + panic!("the preview should draw the custom arrowhead"); + }; + // The preview has 10 points above the line. At the minimum weight, 60 units would need 15. + assert_eq!(head.stop, Some(0.5)); + } + #[test] fn while_typing_the_panel_strokes_the_selected_characters() { use vectorcraft_doc::{LineJoin, NodeKind}; From 3e596a792756db5a6dbea27923cf495c00cf41da Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 26 Nov 2026 12:53:44 -0800 Subject: [PATCH 141/151] Keep Links row menus with their source document --- crates/ui-egui/src/panels/links.rs | 18 ++++++++---- crates/ui-egui/src/panels/tests_links.rs | 35 ++++++++++++++++++++++++ 2 files changed, 47 insertions(+), 6 deletions(-) diff --git a/crates/ui-egui/src/panels/links.rs b/crates/ui-egui/src/panels/links.rs index 72c90a8efc..87b574f820 100644 --- a/crates/ui-egui/src/panels/links.rs +++ b/crates/ui-egui/src/panels/links.rs @@ -96,7 +96,8 @@ pub(crate) struct LinksModel { pub(super) show: Option<(u64, u64)>, nested: NestedPicks, selection: Selection, - menu: Option, + /// The document uid and row ID whose context menu is open. + menu: Option<(u64, u64)>, } /// `links.list` and the first selected image's `links.info`, with what they were fetched for. @@ -710,13 +711,16 @@ fn act(app: &mut VectorcraftApp, act: Act, target: Option) { /// The Links panel: the images as a list with a footer of link actions and the Link Info section. pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { drop_stale_picks(app); + let uid = app.session.active().map(|st| st.uid); + if app.ui.links.menu.is_some_and(|(document, _)| Some(document) != uid) { + app.ui.links.menu = None; + } let Some(mut cache) = cached(app, ui.ctx()) else { Panel::new(tl!("Links")).show(ui, |ui, _| { Text::new(tl!("No document")).shade(Shade::Muted).show(ui); }); return; }; - let uid = app.session.active().map(|st| st.uid); let reveal = app.ui.links.show.take().filter(|(doc, _)| Some(*doc) == uid).map(|(_, id)| id); let listed = |cache: &Cache, id: u64| cache.list["links"].as_array().is_some_and(|rows| rows.iter().any(|r| r["id"].as_u64() == Some(id))); // A Show filter that leaves the requested row out goes back to Show All. @@ -730,7 +734,7 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { let selected = selected_links(app); let mut selection = std::mem::take(&mut app.ui.links.selection); selection.items = selected.clone(); - let open_menu = app.ui.links.menu; + let open_menu = app.ui.links.menu.map(|(_, row)| row); let units = app.session.general_unit(); let view: &VectorcraftApp = app; @@ -808,8 +812,8 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { let items = app.ui.links.selection.items.clone(); apply_selection(app, rows_of(&cache), items); } - if menu_for.is_some() { - app.ui.links.menu = menu_for; + if let Some(row) = menu_for { + app.ui.links.menu = uid.map(|document| (document, row)); } if let Some(id) = activated { go_to(app, id); @@ -828,7 +832,9 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { } if let Some((a, id)) = row_act { app.ui.links.menu = None; - act(app, a, Some(id)); + if app.session.active().map(|st| st.uid) == uid { + act(app, a, Some(id)); + } } } diff --git a/crates/ui-egui/src/panels/tests_links.rs b/crates/ui-egui/src/panels/tests_links.rs index 7c07781d02..6f9a6c5046 100644 --- a/crates/ui-egui/src/panels/tests_links.rs +++ b/crates/ui-egui/src/panels/tests_links.rs @@ -663,6 +663,41 @@ fn unembed_writes_several_images_to_one_picked_folder() { assert_eq!(app.ui.status, format!("Unembedded 2 images to {picked}")); } +#[test] +fn switching_documents_dismisses_a_links_row_menu() { + let dir = Folder::new("context-switched-document"); + let (mut app, first, _) = app(&dir); + let source = app.session.active().unwrap().uid; + app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); + let path = dir.file("other.png", &png(40, 20)); + let second = app.run("file.place", json!({"path": path, "at": [100, 100]})).unwrap()["ids"][0].as_u64().unwrap(); + let destination = app.session.active().unwrap().uid; + assert_eq!(first, second, "the two documents have different images at the same local ID"); + app.run("window.previousDocument", json!({})).unwrap(); + + let mut panel = Panel::new(app, super::links::show); + let activate = |panel: &mut Panel, index, document| { + panel.app().session.execute("document.activate", &json!({"index": index})).unwrap(); + panel.frame(); + panel.frame(); + assert_eq!(panel.app().session.active().unwrap().uid, document); + }; + panel.secondary_click("linked.png"); + assert!(panel.menu_item_enabled("Embed Image")); + activate(&mut panel, 1, destination); + assert!(!panel.shows("Embed Image"), "the other document must not inherit the row menu"); + assert_eq!(panel.app().run("links.info", json!({"id": second})).unwrap()["linked"], true); + + activate(&mut panel, 0, source); + assert!(!panel.shows("Embed Image"), "switching back must not revive the menu"); + assert_eq!(panel.app().run("links.info", json!({"id": first})).unwrap()["linked"], true); + + activate(&mut panel, 1, destination); + panel.secondary_click("other.png"); + panel.click_menu_item("Embed Image"); + assert_eq!(panel.app().run("links.info", json!({"id": second})).unwrap()["status"], "embedded"); +} + #[test] fn right_click_context_menu_in_links_panel() { let dir = Folder::new("context-menu"); From fc47ab939d928aaf24402a379260fa69a07b7331 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 26 Nov 2026 12:54:23 -0800 Subject: [PATCH 142/151] Keep Define Grid changes on their source document --- .../ui-egui/src/dialogs/perspective_grid.rs | 24 +++++++++++--- .../ui-egui/src/dialogs/tests_perspective.rs | 33 +++++++++++++++++++ 2 files changed, 52 insertions(+), 5 deletions(-) diff --git a/crates/ui-egui/src/dialogs/perspective_grid.rs b/crates/ui-egui/src/dialogs/perspective_grid.rs index bed5ab085b..d75a811a74 100644 --- a/crates/ui-egui/src/dialogs/perspective_grid.rs +++ b/crates/ui-egui/src/dialogs/perspective_grid.rs @@ -134,6 +134,7 @@ fn open_on(app: &mut VectorcraftApp, def: GridDefinition, mode: GridMode) -> Res let dialog = GridDialog::new( def, mode, + app.session.active().map(|st| st.uid), (general_lengths(app).pixels_per_inch, app.session.prefs.numbers_without_units_are_points), app.session.perspective_presets(), app.session.new_perspective_preset_name(), @@ -171,6 +172,8 @@ pub fn open_edit(app: &mut VectorcraftApp, original: Option<&str>, base: &str) - pub(super) struct GridDialog { id: DialogId, mode: GridMode, + /// The document whose grid Define Grid edits. + source_document: Option, draft: GridDraft, /// The presets the Preset row offers, as the document and the preferences have them. presets: Vec, @@ -190,10 +193,18 @@ pub(super) struct GridDialog { } impl GridDialog { - fn new(def: GridDefinition, mode: GridMode, (ppi, bare_points): (f64, bool), presets: Vec, new_name: String) -> Self { + fn new( + def: GridDefinition, + mode: GridMode, + source_document: Option, + (ppi, bare_points): (f64, bool), + presets: Vec, + new_name: String, + ) -> Self { let mut dialog = GridDialog { id: dialog_id(KIND), mode, + source_document, draft: GridDraft { def }, presets: Vec::new(), rows: Vec::new(), @@ -516,9 +527,12 @@ enum Next { Presets(String), } -fn file(app: &mut VectorcraftApp, mode: &GridMode, def: &GridDefinition) -> Result { +fn file(app: &mut VectorcraftApp, mode: &GridMode, source_document: Option, def: &GridDefinition) -> Result { let mut params = serde_json::to_value(def).map_err(|e| e.to_string())?; if *mode == GridMode::Define { + if app.session.active().map(|st| st.uid) != source_document { + return Err(tl!("Define Grid can only change the document where it was opened.").to_owned()); + } app.run("perspective.grid.define", params)?; return Ok(Next::Close); } @@ -546,10 +560,10 @@ pub(crate) fn pump(app: &mut VectorcraftApp, _ctx: &egui::Context) { let filed = dialogs.with(|host| { let dialog = host.get_mut::()?; dialog.set_presets(presets, new_name); - dialog.held.take().map(|def| (dialog.mode.clone(), def)) + dialog.held.take().map(|def| (dialog.mode.clone(), dialog.source_document, def)) }); - let Some((mode, def)) = filed else { return }; - let next = file(app, &mode, &def); + let Some((mode, source_document, def)) = filed else { return }; + let next = file(app, &mode, source_document, &def); if let Err(why) = &next { app.status(why.clone()); } diff --git a/crates/ui-egui/src/dialogs/tests_perspective.rs b/crates/ui-egui/src/dialogs/tests_perspective.rs index 90af85ee0c..089296ae7a 100644 --- a/crates/ui-egui/src/dialogs/tests_perspective.rs +++ b/crates/ui-egui/src/dialogs/tests_perspective.rs @@ -104,6 +104,39 @@ fn define_grid_opens_on_the_grid_and_applies_its_fields() { assert_eq!((grid(&app).cell, grid(&app).viewing_angle()), (n.cell, n.viewing_angle())); } +#[test] +fn define_grid_applies_only_to_the_document_where_it_opened() { + let mut app = app(); + app.run("file.new", json!({"width": 800, "height": 600})).unwrap(); + let destination = app.session.active().unwrap(); + let destination_uid = destination.uid; + let destination_undo = destination.history.undo.len(); + let destination_grid = grid(&app); + app.run("document.activate", json!({"index": 0})).unwrap(); + let source_uid = app.session.active().unwrap().uid; + app.run("ui.perspectiveGridDialog", json!({})).unwrap(); + set(&mut app, "rightColor", json!("#112233")).unwrap(); + let ctx = window(&app); + let id = dialog_id(super::perspective_grid::KIND); + host(&app, |h| { + assert!(!h.confirm_by_id(&ctx, id)); + assert_eq!(h.held_state(id), Some(HeldOk::Waiting)); + }); + + app.run("document.activate", json!({"index": 1})).unwrap(); + super::perspective_grid::pump(&mut app, &ctx); + assert_eq!(app.session.active().unwrap().uid, destination_uid); + assert_eq!(grid(&app), destination_grid, "the first document's draft leaves the active grid alone"); + assert_eq!(app.session.active().unwrap().history.undo.len(), destination_undo); + assert!(matches!(host(&app, |h| h.held_state(id)), Some(HeldOk::Refused(_)))); + + app.run("document.activate", json!({"index": 0})).unwrap(); + assert_eq!(app.session.active().unwrap().uid, source_uid); + ok(&mut app); + assert_eq!(kind(&app), None); + assert_eq!(grid(&app).right_color.hex(), "#112233"); +} + #[test] fn define_grid_loads_and_saves_presets() { let mut app = app(); From 8901f9ac4e3683bbe8e79ba3ef3e4dff881446a6 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 26 Nov 2026 12:58:23 -0800 Subject: [PATCH 143/151] Keep Artboard Options attached to their original target --- .../ui-egui/src/dialogs/artboard_options.rs | 117 +++++++++++++++--- 1 file changed, 100 insertions(+), 17 deletions(-) diff --git a/crates/ui-egui/src/dialogs/artboard_options.rs b/crates/ui-egui/src/dialogs/artboard_options.rs index b49ab8d83f..cb1c6337e5 100644 --- a/crates/ui-egui/src/dialogs/artboard_options.rs +++ b/crates/ui-egui/src/dialogs/artboard_options.rs @@ -137,8 +137,7 @@ impl ArtboardOptionsValue { } } -/// What the dialog shows but does not edit; read from the app when it opens, since a modal dialog's -/// document, presets and preferences cannot change while it is open. +/// What the dialog shows but does not edit, read from the app when it opens. struct Setup { /// The lengths the fields keep and show. lengths: LengthUnits, @@ -152,9 +151,17 @@ struct Setup { fit_bounds: [Option; 2], } +#[derive(Clone, Copy)] +struct Target { + document: u64, + /// The current artboard's ID, or no ID while creating a new artboard. + artboard: Option, +} + /// Artboard Options on the dialog host: the artboard's value, the held OK and the color requests. pub struct ArtboardOptionsDialog { id: DialogId, + target: Target, value: ArtboardOptionsValue, setup: Setup, held: HeldAnswer, @@ -162,8 +169,8 @@ pub struct ArtboardOptionsDialog { } impl ArtboardOptionsDialog { - fn new(value: ArtboardOptionsValue, setup: Setup) -> Self { - ArtboardOptionsDialog { id: dialog_id(KIND), value, setup, held: HeldAnswer::new(), requests: HostRequests::new() } + fn new(target: Target, value: ArtboardOptionsValue, setup: Setup) -> Self { + ArtboardOptionsDialog { id: dialog_id(KIND), target, value, setup, held: HeldAnswer::new(), requests: HostRequests::new() } } } @@ -546,13 +553,15 @@ pub(crate) fn active_index(app: &VectorcraftApp) -> usize { /// Opens the dialog over `value`, with the preferences, the shared reference point and what the dialog /// shows read from the app. -fn present(app: &mut VectorcraftApp, mut value: ArtboardOptionsValue) -> Result { +fn present(app: &mut VectorcraftApp, mut value: ArtboardOptionsValue, artboard: Option) -> Result { let host = app.dialogs().ok_or("no window")?; + let st = app.session.active().ok_or("no document")?; + let target = Target { document: st.uid, artboard }; + let artwork = vectorcraft_render::encode::art_bounds(&st.doc); let [(_, fade), (_, update_while_dragging)] = global_fields(app); (value.fade, value.update_while_dragging, value.reference) = (fade, update_while_dragging, app.ui.transform_panel.reference_point); let fills = fill_colors(app); value.seed_customs(&fills); - let artwork = app.session.active().and_then(|st| vectorcraft_render::encode::art_bounds(&st.doc)); let setup = Setup { lengths: crate::canvas::rulers::general_lengths(app), origin: app.ruler_origin(), @@ -560,7 +569,7 @@ fn present(app: &mut VectorcraftApp, mut value: ArtboardOptionsValue) -> Result< fills, fit_bounds: [artwork, app.selection_bounds()], }; - host.with(|h| h.open(ArtboardOptionsDialog::new(value, setup))); + host.with(|h| h.open(ArtboardOptionsDialog::new(target, value, setup))); Ok(json!({ "dialog": KIND })) } @@ -569,6 +578,7 @@ pub fn open(app: &mut VectorcraftApp) -> Result { let index = active_index(app); let st = app.session.active().ok_or("no document")?; let a = st.doc.artboards.get(index).ok_or("no artboard")?; + let artboard = a.id; let r = a.rect; let value = ArtboardOptionsValue { index, @@ -585,7 +595,7 @@ pub fn open(app: &mut VectorcraftApp) -> Result { pixel_aspect: a.video_ruler_pixel_aspect_ratio, ..Default::default() }; - present(app, value) + present(app, value, Some(artboard)) } /// `ui.newArtboard` (Alt-click on the Artboards panel's New Artboard): Artboard Options for a new @@ -605,7 +615,7 @@ pub fn open_new(app: &mut VectorcraftApp) -> Result { pixel_aspect: 1.0, ..Default::default() }; - present(app, value) + present(app, value, None) } /// Runs once per frame after the shell pass: runs the artboard command of a filed OK and answers it @@ -613,12 +623,15 @@ pub fn open_new(app: &mut VectorcraftApp) -> Result { /// point picked in the dialog. pub(crate) fn pump(app: &mut VectorcraftApp, _ctx: &egui::Context) { let Some(host) = app.dialogs() else { return }; - let Some((held, reference)) = host.with(|h| h.get_mut::().map(|d| (d.held.take(), d.value.reference))) else { return }; + let Some((target, held, reference)) = host.with(|h| h.get_mut::().map(|d| (d.target, d.held.take(), d.value.reference))) + else { + return; + }; if app.ui.transform_panel.reference_point != reference { app.ui.transform_panel.reference_point = reference; } if let Some(value) = held { - let answer = confirm(app, &value).map(drop).map_err(Label::from); + let answer = confirm(app, target, &value).map(drop).map_err(Label::from); host.with(|h| { if let Some(d) = h.get_mut::() { d.held.answer(answer); @@ -633,21 +646,28 @@ pub(crate) fn pump(app: &mut VectorcraftApp, _ctx: &egui::Context) { /// used (its column and row), all in one undo step. Fitting applies only to this artboard and never /// moves its artwork. The Global checkboxes' preferences are set only after the artboard command /// succeeds, so an error leaves them as they were. -fn confirm(app: &mut VectorcraftApp, v: &ArtboardOptionsValue) -> Result { +fn confirm(app: &mut VectorcraftApp, target: Target, v: &ArtboardOptionsValue) -> Result { + let st = app + .session + .active() + .filter(|st| st.uid == target.document) + .ok_or(tl!("Artboard Options can only change the document where it was opened."))?; let globals = global_changes(app, v); if v.new { let r = confirm_new(app, v)?; set_globals(app, globals)?; return Ok(r); } - let p = v.params(); - let was = app.session.active().and_then(|st| st.doc.artboards.get(v.index)).map(|a| a.rect); - let changed = |k: &str, old: Option| p[k].as_f64().filter(|n| old.is_some_and(|old| (n - old).abs() > 1e-6)); - let (w, h) = (changed("width", was.map(|r| r.width())), changed("height", was.map(|r| r.height()))); + let (index, board) = + st.doc.artboards.iter().enumerate().find(|(_, board)| Some(board.id) == target.artboard).ok_or(tl!("This artboard was removed."))?; + let mut p = v.params(); + p["index"] = json!(index); + let changed = |k: &str, old: f64| p[k].as_f64().filter(|n| (n - old).abs() > 1e-6); + let (w, h) = (changed("width", board.rect.width()), changed("height", board.rect.height())); let refi = v.ref_y.min(2) * 3 + v.ref_x.min(2); let mut entries = vec![]; if !v.fit && (v.size_choice.is_some() || w.is_some() || h.is_some()) { - for i in crate::panels::artboards::resized_with(app, v.index).into_iter().filter(|i| *i != v.index) { + for i in crate::panels::artboards::resized_with(app, index).into_iter().filter(|i| *i != index) { if let Some(r) = app.session.active().and_then(|st| st.doc.artboards.get(i)).map(|a| a.rect) { let (w, h) = if let Some(choice) = v.size_choice { let Some((w, h)) = choice.size_for(r.width(), r.height()) else { continue }; @@ -753,6 +773,69 @@ mod tests { app.session.doc().unwrap().history.undo.len() } + #[test] + fn confirmation_follows_the_original_artboard_after_reorder() { + let mut app = app(); + app.run("artboard.new", json!({"x": 400, "y": 0, "width": 100, "height": 50})).unwrap(); + crate::panels::artboards::select(&mut app, 0); + let original = app.session.active().unwrap().doc.artboards[0].id; + open(&mut app).unwrap(); + set(&app, &[("name", json!("Renamed"))]).unwrap(); + + app.run("artboard.reorder", json!({"index": 0, "to": 1})).unwrap(); + assert_eq!(app.session.active().unwrap().doc.artboards[1].id, original); + let undo = undo_len(&app); + ok(&mut app).unwrap(); + let artboards = &app.session.active().unwrap().doc.artboards; + assert_eq!((artboards[0].name.as_str(), artboards[1].name.as_str()), ("Artboard 2", "Renamed")); + assert_eq!(undo_len(&app), undo + 1); + } + + #[test] + fn confirmation_refuses_to_edit_or_add_artboards_in_another_document() { + for create in [false, true] { + let mut app = app(); + app.run("file.new", json!({"width": 300, "height": 200})).unwrap(); + app.run("document.activate", json!({"index": 0})).unwrap(); + if create { + open_new(&mut app).unwrap(); + } else { + open(&mut app).unwrap(); + } + set(&app, &[("name", json!("Source"))]).unwrap(); + + app.run("document.activate", json!({"index": 1})).unwrap(); + let undo = undo_len(&app); + let answer = ok(&mut app); + let artboards = &app.session.active().unwrap().doc.artboards; + assert_eq!((artboards.len(), artboards[0].name.as_str()), (1, "Artboard 1")); + assert_eq!(undo_len(&app), undo); + assert!(answer.is_err() && is_open(&app)); + + app.run("document.activate", json!({"index": 0})).unwrap(); + ok(&mut app).unwrap(); + let artboards = &app.session.active().unwrap().doc.artboards; + assert_eq!(artboards.len(), if create { 2 } else { 1 }); + assert_eq!(artboards.last().unwrap().name, "Source"); + } + } + + #[test] + fn confirmation_refuses_to_edit_a_deleted_artboards_replacement() { + let mut app = app(); + app.run("artboard.new", json!({"x": 400, "y": 0, "width": 100, "height": 50})).unwrap(); + crate::panels::artboards::select(&mut app, 0); + open(&mut app).unwrap(); + set(&app, &[("name", json!("Renamed"))]).unwrap(); + + app.run("artboard.delete", json!({"index": 0})).unwrap(); + let undo = undo_len(&app); + let answer = ok(&mut app); + assert_eq!(app.session.active().unwrap().doc.artboards[0].name, "Artboard 2"); + assert_eq!(undo_len(&app), undo); + assert!(answer.is_err() && is_open(&app)); + } + /// A new X moves the art only with Move Artwork with Artboard on, and Undo restores the document. #[test] fn position_moves_art_only_with_the_tool_option_on() { From f4184d5c5117d891daaaadb6067d86eb7e1ff48b Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 26 Nov 2026 13:04:03 -0800 Subject: [PATCH 144/151] Keep Text Styles row menus with their source document --- crates/ui-egui/src/panels/text_styles.rs | 8 +++- .../ui-egui/src/panels/text_styles/tests.rs | 48 +++++++++++++++++++ 2 files changed, 54 insertions(+), 2 deletions(-) diff --git a/crates/ui-egui/src/panels/text_styles.rs b/crates/ui-egui/src/panels/text_styles.rs index dbd7447b34..bfcffa6e65 100644 --- a/crates/ui-egui/src/panels/text_styles.rs +++ b/crates/ui-egui/src/panels/text_styles.rs @@ -66,6 +66,8 @@ impl StylesPanels { pub(crate) struct StylesPanel { /// The uid of the document the highlight was made in. document: Option, + /// Changes when the panel switches documents, so reopening a document cannot restore its old popup. + scope_generation: u64, /// The highlighted styles, in the order they were picked. highlight: Vec, /// The selection's lead style. @@ -83,7 +85,7 @@ fn highlighted(app: &mut VectorcraftApp, kind: Kind, listed: &[&str]) -> Vec = listed.iter().enumerate().map(|(i, name)| TextStyleRow::new(i as u64, super::label_or_name(name, i == 0))).collect(); @@ -271,7 +274,8 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui, kind: Kind) { if let Some(id) = reveal.as_deref().and_then(id_of) { list = list.reveal(id); } - let out = list.show(ui); + // The framework's row menu and footer drag use list indices that are local to this document. + let out = ui.push_id(("text-styles-document", kind.panel_kind(), scope), |ui| list.show(ui)).inner; let name_of = |id: &u64| listed.get(*id as usize).map(|n| n.to_string()); let panel = app.ui.text_styles.of(kind); panel.highlight = sel.items.iter().filter_map(name_of).collect(); diff --git a/crates/ui-egui/src/panels/text_styles/tests.rs b/crates/ui-egui/src/panels/text_styles/tests.rs index 3e80710437..5144f8ce9a 100644 --- a/crates/ui-egui/src/panels/text_styles/tests.rs +++ b/crates/ui-egui/src/panels/text_styles/tests.rs @@ -4,6 +4,54 @@ use crate::tests::picks::{answer_dialog, cancel_dialog, open_dialogs, poll, scri use crate::tests::synthetic::key_frame; use vectorcraft_doc::{NodeId, NodeKind}; +#[test] +fn switching_documents_dismisses_text_styles_row_menus() { + use crate::tests::panel_harness::Panel; + use vectorcraft_engine::Session; + + for kind in [Kind::Char, Kind::Para] { + let mut app = crate::testing::windowed(VectorcraftApp::new(Session::new(), Default::default())); + let command = format!("{}.new", kind.prefix()); + app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); + app.run(&command, json!({"name": "First Style"})).unwrap(); + let first = style_id(&mut app, kind, "First Style"); + let source = app.session.active().unwrap().uid; + app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); + app.run(&command, json!({"name": "Second Style"})).unwrap(); + let second = style_id(&mut app, kind, "Second Style"); + let destination = app.session.active().unwrap().uid; + assert_eq!(first, second, "the two documents carry styles at the same list index"); + app.run("window.previousDocument", json!({})).unwrap(); + + let draw: fn(&mut VectorcraftApp, &mut Ui) = match kind { + Kind::Char => |app, ui| show(app, ui, Kind::Char), + Kind::Para => |app, ui| show(app, ui, Kind::Para), + }; + let mut panel = Panel::new(app, draw); + let activate = |panel: &mut Panel, index, document| { + panel.app().session.execute("document.activate", &json!({"index": index})).unwrap(); + panel.frame(); + panel.frame(); + assert_eq!(panel.app().session.active().unwrap().uid, document); + }; + let has_copy = |panel: &Panel, name: &str| styles(&mut panel.app(), kind).iter().any(|style| style.0 == name); + panel.secondary_click("First Style"); + assert!(panel.menu_item_enabled("Duplicate Style")); + activate(&mut panel, 1, destination); + assert!(!panel.shows("Duplicate Style"), "the new document does not inherit the row menu"); + assert!(!has_copy(&panel, "Second Style copy")); + + activate(&mut panel, 0, source); + assert!(!panel.shows("Duplicate Style"), "the old row menu does not reappear"); + assert!(!has_copy(&panel, "First Style copy")); + + activate(&mut panel, 1, destination); + panel.secondary_click("Second Style"); + panel.click_menu_item("Duplicate Style"); + assert!(has_copy(&panel, "Second Style copy")); + } +} + // PLAN: assumed type-w19 items reachable through `super::*`: `run_action(app, kind, action)`, // `StylesPanel { highlight: Vec, .. }` and `StylesPanels { char, para, made }` at // `app.ui.text_styles`, `highlighted(app, kind, listed: &[&str]) -> Vec`, `TextStyleAction`, and a From e5c631732427c8cb1d70734e05ae213085eb4dc2 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 26 Nov 2026 13:14:24 -0800 Subject: [PATCH 145/151] Keep Rename Artboards on its original selection --- .../ui-egui/src/dialogs/rename_artboards.rs | 69 ++++++++++++++++--- 1 file changed, 61 insertions(+), 8 deletions(-) diff --git a/crates/ui-egui/src/dialogs/rename_artboards.rs b/crates/ui-egui/src/dialogs/rename_artboards.rs index d6b74551f5..6eb9001c3b 100644 --- a/crates/ui-egui/src/dialogs/rename_artboards.rs +++ b/crates/ui-egui/src/dialogs/rename_artboards.rs @@ -19,14 +19,15 @@ pub(crate) const CMD: &str = "artboard.rename"; /// for several. pub(crate) fn open(app: &mut VectorcraftApp) -> Result { let ctx = app.ui_ctx.clone().ok_or("no window")?; - let (indices, name) = app.session.active().map_or((vec![], String::new()), |st| { - let indices = crate::panels::artboards::picked(app, st.doc.artboards.len()); - let name = match indices.as_slice() { - [one] => st.doc.artboards.get(*one).map_or("", |a| a.name.as_str()), - _ => "", - }; - (indices, name.to_owned()) - }); + let st = app.session.active().ok_or_else(|| tl!("No document").to_owned())?; + let document = st.uid; + let selected: Vec<_> = + crate::panels::artboards::picked(app, st.doc.artboards.len()).into_iter().filter_map(|index| st.doc.artboards.get(index)).collect(); + let name = match selected.as_slice() { + [one] => one.name.clone(), + _ => String::new(), + }; + let artboards: Vec<_> = selected.iter().map(|board| board.id).collect(); let mut fields = DialogFields::new(); fields.set("name", name); let dialog = HostedParamDialog::command(&ctx, CMD, fields, |fields| { @@ -39,6 +40,13 @@ pub(crate) fn open(app: &mut VectorcraftApp) -> Result { if name.trim().is_empty() { return Ok(()); } + let st = + app.session.active().filter(|st| st.uid == document).ok_or_else(|| tl!("This dialog was opened in a different document.").to_owned())?; + let indices = artboards + .iter() + .map(|id| st.doc.artboards.iter().position(|board| board.id == *id)) + .collect::>>() + .ok_or_else(|| tl!("One of the artboards being renamed no longer exists.").to_owned())?; if let Err(e) = app.run(CMD, json!({ "indices": indices, "name": name })) { app.status(e); } @@ -105,6 +113,51 @@ mod tests { assert_eq!(app.session.active().unwrap().history.undo.len(), steps + 1, "one undo step"); } + #[test] + fn rename_follows_the_original_artboards_after_reordering() { + let mut app = app(); + app.session.set_tool_option("selected", &json!([0, 2])); + open(&mut app).unwrap(); + app.run("artboard.reorder", json!({"index": 0, "to": 2})).unwrap(); + assert_eq!(names(&app), ["Artboard 2", "Artboard 3", "Artboard 1"]); + let steps = app.session.active().unwrap().history.undo.len(); + rename(&mut app, "Page"); + assert_eq!(names(&app), ["Artboard 2", "Page-1", "Page-2"]); + assert_eq!(app.session.active().unwrap().history.undo.len(), steps + 1); + } + + #[test] + fn rename_waits_for_the_document_it_opened_in() { + let mut app = app(); + open(&mut app).unwrap(); + app.run("file.new", json!({"width": 100, "height": 50, "artboards": 3})).unwrap(); + let steps = app.session.active().unwrap().history.undo.len(); + rename(&mut app, "Source only"); + assert_eq!(names(&app), ["Artboard 1", "Artboard 2", "Artboard 3"]); + assert_eq!(app.session.active().unwrap().history.undo.len(), steps); + assert!(app.any_dialog_open(), "the original document can still answer"); + + app.session.execute("document.activate", &json!({"index": 0})).unwrap(); + rename(&mut app, "Source only"); + assert_eq!(names(&app), ["Source only", "Artboard 2", "Artboard 3"]); + assert!(!app.any_dialog_open()); + } + + #[test] + fn rename_leaves_the_other_targets_alone_if_an_original_artboard_was_removed() { + let mut app = app(); + app.session.set_tool_option("selected", &json!([0, 2])); + open(&mut app).unwrap(); + app.run("artboard.delete", json!({"index": 2})).unwrap(); + app.run("artboard.duplicate", json!({"index": 1})).unwrap(); + let before = names(&app); + let steps = app.session.active().unwrap().history.undo.len(); + rename(&mut app, "Page"); + assert_eq!(names(&app), before); + assert_eq!(app.session.active().unwrap().history.undo.len(), steps); + assert!(app.any_dialog_open()); + } + /// OK with an empty name or the name the artboard already has records no undo step. #[test] fn nothing_changes_for_an_empty_or_unchanged_name() { From 492e0c72d76437bd62b15deaf616166af07a10c9 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 26 Nov 2026 13:06:04 -0800 Subject: [PATCH 146/151] Keep File Info confirmation with its document --- crates/ui-egui/src/dialogs/file_info.rs | 72 ++++++++++++++++++++++--- 1 file changed, 66 insertions(+), 6 deletions(-) diff --git a/crates/ui-egui/src/dialogs/file_info.rs b/crates/ui-egui/src/dialogs/file_info.rs index e43435b5ae..fffa334f21 100644 --- a/crates/ui-egui/src/dialogs/file_info.rs +++ b/crates/ui-egui/src/dialogs/file_info.rs @@ -55,8 +55,14 @@ type Info = Map; pub fn open(app: &mut VectorcraftApp) -> Result { let fields = app.session.execute("file.info", &json!({})).map_err(|e| e.to_string())?; let fields = fields.as_object().cloned().ok_or("file.info gave no fields")?; - let ok = |app: &mut VectorcraftApp, fields: &Info| app.run("file.info", Value::Object(fields.clone())).map(|_| ()); - crate::dialogs::host::open_held(app, FileInfoDialog::new(fields), ok).ok_or("no window")?; + let document = app.session.active().ok_or("no document")?.uid; + let ok = |app: &mut VectorcraftApp, (document, fields): &(u64, Info)| { + if !app.session.active().is_some_and(|active| active.uid == *document) { + return Err(tl!("File Info can only change the document it was opened for.").to_owned()); + } + app.run("file.info", Value::Object(fields.clone())).map(|_| ()) + }; + crate::dialogs::host::open_held(app, FileInfoDialog::new(document, fields), ok).ok_or("no window")?; Ok(Value::Null) } @@ -215,6 +221,7 @@ impl Templates { /// The File Info dialog: a form over the fields `file.info` reports, whose OK is held for the app. pub(crate) struct FileInfoDialog { id: DialogId, + document: u64, open: bool, /// OK files its answer for the app instead of closing ([`HoldsOk::held_ok`]). hold: bool, @@ -230,9 +237,10 @@ pub(crate) struct FileInfoDialog { } impl FileInfoDialog { - fn new(value: Info) -> Self { + fn new(document: u64, value: Info) -> Self { FileInfoDialog { id: dialog_id(KEY), + document, open: true, hold: false, value, @@ -371,15 +379,15 @@ fn import_options(ui: &mut egui::Ui, mode: &mut &'static str) -> Option { } impl HoldsOk for FileInfoDialog { - type Answer = Info; + type Answer = (u64, Info); fn held_ok(mut self) -> Self { self.hold = true; self } - fn take_ok(&mut self) -> Option { - self.held.take() + fn take_ok(&mut self) -> Option { + self.held.take().map(|fields| (self.document, fields)) } fn answer_ok(&mut self, answer: Result<(), Label>) { @@ -674,6 +682,58 @@ mod tests { assert!(with_dialog(&app, |_| ()).is_some()); } + #[test] + fn a_file_info_confirmation_stays_with_its_document() { + let mut app = windowed(); + for (title, author) in [("Source", "Ada"), ("Destination", "Grace")] { + app.run("file.new", json!({"width": 200, "height": 200})).unwrap(); + app.run("file.info", json!({"title": title, "author": author})).unwrap(); + } + let activate = |app: &mut VectorcraftApp, index| app.run("document.activate", json!({"index": index})).unwrap(); + activate(&mut app, 0); + let a_undo = app.session.active().unwrap().history.undo.len(); + app.run("ui.fileInfoDialog", json!({})).unwrap(); + set(&app, "title", json!("Revised Source")).unwrap(); + set(&app, PENDING, json!("print")).unwrap(); + let ctx = app.ui_ctx.clone().unwrap(); + assert!(!app.dialogs().unwrap().with(|host| host.confirm_by_id(&ctx, dialog_id(KEY))), "the edit waits for the application"); + + activate(&mut app, 1); + let before = app.session.active().unwrap(); + let document = before.doc.clone(); + let b_undo = before.history.undo.len(); + crate::dialogs::host::pump(&mut app, &ctx); + let after = app.session.active().unwrap(); + assert_eq!(after.doc.info_title(), document.info_title(), "the destination's title stays untouched"); + assert_eq!(after.doc.metadata, document.metadata, "the destination's metadata stays untouched"); + assert_eq!(after.history.undo.len(), b_undo); + assert!(matches!(held_state(&app), Some(HeldOk::Refused(_)))); + + activate(&mut app, 0); + assert!(press_ok(&mut app), "a fresh confirmation can apply the original draft"); + let source = app.session.active().unwrap(); + assert_eq!(source.doc.info_title(), "Revised Source"); + assert_eq!(source.doc.metadata.author, "Ada"); + assert_eq!(source.doc.metadata.keywords, ["print"]); + assert_eq!(source.history.undo.len(), a_undo + 1); + } + + #[test] + fn a_reopened_file_info_confirmation_uses_the_new_drafts_document() { + let mut app = windowed(); + app.run("file.new", json!({"width": 200, "height": 200})).unwrap(); + app.run("file.new", json!({"width": 300, "height": 300})).unwrap(); + app.run("document.activate", json!({"index": 0})).unwrap(); + app.run("ui.fileInfoDialog", json!({})).unwrap(); + app.run("document.activate", json!({"index": 1})).unwrap(); + app.run("ui.fileInfoDialog", json!({})).unwrap(); + set(&app, "title", json!("Revised Destination")).unwrap(); + assert!(press_ok(&mut app)); + assert_eq!(app.session.active().unwrap().doc.info_title(), "Revised Destination"); + app.run("document.activate", json!({"index": 0})).unwrap(); + assert!(app.session.active().unwrap().history.undo.is_empty()); + } + #[test] fn an_imported_template_fills_the_fields_and_ok_is_one_undo_step() { let dir = vectorcraft_testkit::TempDir::new("ui-file-info-template"); From 84480460687248db4c5845b43c3c89aa4f3694f8 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 26 Nov 2026 13:16:41 -0800 Subject: [PATCH 147/151] Keep Flattener Preview settings within narrow panels --- .../ui-egui/src/panels/flattener_preview.rs | 107 +++++++++++++++--- 1 file changed, 92 insertions(+), 15 deletions(-) diff --git a/crates/ui-egui/src/panels/flattener_preview.rs b/crates/ui-egui/src/panels/flattener_preview.rs index e2c724fe2f..c55c06b1c3 100644 --- a/crates/ui-egui/src/panels/flattener_preview.rs +++ b/crates/ui-egui/src/panels/flattener_preview.rs @@ -13,9 +13,9 @@ use std::sync::Arc; use craft::behavior::CanvasTransform; use craft::ui::buttons::Button; -use craft::ui::contract::{Bind, Entry, Props as _, Show as _, ShowContainer as _}; +use craft::ui::contract::{Bind, Entry, Props as _, Show as _, ShowContainer as _, Sizing}; use craft::ui::display::{Divider, Shade, Text}; -use craft::ui::layout_components::Row; +use craft::ui::layout_components::{Row, Stack}; use craft::ui::menu::PanelRow; use craft::ui::patterns::form_dialogs::{DialogFields, ParamRows, PreviewPane, PreviewView, PreviewZoom}; use craft::ui::pickers::Select; @@ -200,30 +200,43 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { } // The highlighted art takes the theme's error colour. let highlight = rgba_color(Env::of(ui).tokens.tokens().color.status.bad.solid); + let compact = ui.available_width() < Env::of(ui).tokens.size.plot.width; let mut set = app.ui.flattener_preview.clone(); let mut refresh_now = false; - Row::new().show(ui, |ui, _| { + Row::new().fill_width().wrap(true).show(ui, |ui, _| { refresh_now = Button::new(tl!("Refresh")).tooltip(tl!("Preview the document as it is now")).show(ui).clicked(); let entries = Highlight::ALL.map(|h| Entry::new(h, h.label())); - Select::new(tl!("Highlight"), Bind::bound(&mut set.highlight), &entries).show(ui); + let picker = Select::new(tl!("Highlight"), Bind::bound(&mut set.highlight), &entries); + let picker = if compact { picker.sizing(Sizing::FillWidth) } else { picker }; + picker.show(ui); }); - Row::new().show(ui, |ui, _| { + Row::new().fill_width().wrap(true).show(ui, |ui, _| { Text::new(tl!("Overprints:")).shade(Shade::Muted).show(ui); let entries = Overprints::ALL.map(|o| Entry::new(o, o.label())); - Select::new(tl!("Overprints"), Bind::bound(&mut set.overprints), &entries).show(ui); + let picker = Select::new(tl!("Overprints"), Bind::bound(&mut set.overprints), &entries); + let picker = if compact { picker.sizing(Sizing::FillWidth) } else { picker }; + picker.show(ui); }); - Row::new().show(ui, |ui, _| { + let preset_id = ui.scope_id().with("flattener-preset-row"); + let mut preset = |ui: &mut Ui| { Text::new(tl!("Preset:")).shade(Shade::Muted).show(ui); let names = flatten::preset_names(app); - let mut fields = DialogFields::from_pairs([("preset", set.preset.clone())]); - flatten::preset_picker(ui, &mut fields, "preset", &names, custom(app)); - if let Some(name) = fields.text("preset") - && name != set.preset + let is_custom = custom(app); + let current = if is_custom { String::new() } else { set.preset.clone() }; + let mut fields = DialogFields::from_pairs([("preset", current.clone())]); + flatten::preset_picker(ui, &mut fields, "preset", &names, is_custom); + if !ui.is_sizing_pass() + && let Some(name) = fields.text("preset").filter(|name| *name != current) && let Some(p) = app.session.flattener_preset(name) { (set.preset, set.options) = (p.name, p.options); } - }); + }; + if compact { + Stack::new().id(preset_id).fill_width().show(ui, |ui, _| preset(ui)); + } else { + Row::new().id(preset_id).fill_width().wrap(true).show(ui, |ui, _| preset(ui)); + } if set.show_options { Divider::horizontal().show(ui); let params = flatten::option_params(&[], ""); @@ -285,11 +298,16 @@ fn preview_area(app: &mut VectorcraftApp, ui: &mut Ui, highlight: egui::Color32, // At scale 1 the picture is the fit of the well (width `w`, height `w / ASPECT`), so the zoom reads relative to the fit. let s = (f64::from(w) / shot.fit.width()).min(f64::from(w / ASPECT) / shot.fit.height()); let size = vec2((shot.fit.width() * s) as f32, (shot.fit.height() * s) as f32); - let out = PreviewPane::new(tl!("Flattener Preview"), SizedTexture::new(tx.id(), size), view) + let pane = PreviewPane::new(tl!("Flattener Preview"), SizedTexture::new(tx.id(), size), view) .aspect(ASPECT) .click_centres(false) - .tooltip(tl!("Click to zoom in, Alt-click to zoom out, drag to pan, double-click to fit")) - .show(ui); + .tooltip(tl!("Click to zoom in, Alt-click to zoom out, drag to pan, double-click to fit")); + let out = if w < Env::of(ui).tokens.size.plot.width { + let (_, room) = ui.allocate_space(vec2(w, w / ASPECT)); + pane.show_at(ui, room) + } else { + pane.show(ui) + }; *view = match out.clicked { Some(at) => { let factor = if craft::ui::runtime::pointer::frame(ui.ctx()).pick_mods.alt { 0.5 } else { 2.0 }; @@ -484,6 +502,65 @@ mod tests { assert_eq!(back.flattener_preview, app.ui.flattener_preview); } + #[test] + fn the_flattener_selectors_and_preview_fit_a_narrow_dock() { + use craft::ui::contract::Role; + + let mut panel = crate::tests::panel_harness::Panel::new(app(), show); + let width = 100.0; + panel.room(vec2(width, 520.0)).frame(); + panel.frame(); + for name in ["Highlight", "Overprints", "Preset:"] { + let rect = panel.rect_role(name, Role::COMBO_BOX); + assert!(rect.left() >= 0.0 && rect.right() <= width, "{name} overflows the dock at {rect:?}"); + } + let pane = panel.rect("Flattener Preview"); + assert!(pane.left() >= 0.0 && pane.right() <= width, "preview overflows the dock at {pane:?}"); + } + + #[test] + fn the_flattener_selectors_keep_their_caption_rows_when_the_panel_is_wide() { + use craft::ui::contract::Role; + + let mut panel = crate::tests::panel_harness::Panel::new(app(), show); + panel.room(vec2(440.0, 600.0)).frame(); + panel.frame(); + for (caption, role, picker) in + [("Refresh", Role::BUTTON, "Highlight"), ("Overprints:", Role::LABEL, "Overprints"), ("Preset:", Role::LABEL, "Preset:")] + { + let row = panel.rect_role(caption, role); + let field = panel.rect_role(picker, Role::COMBO_BOX); + assert!(field.left() >= row.right() && field.center().y >= row.top() && field.center().y <= row.bottom(), "{picker} is below {caption}"); + } + } + + #[test] + fn the_compact_flattener_applies_a_preset_and_refreshes_the_snapshot() { + use craft::ui::contract::Role; + + let mut app = app(); + command(&mut app, &json!({"preset": "high", "options": {"balance": 12}})).unwrap(); + let mut panel = crate::tests::panel_harness::Panel::new(app, show); + panel.room(vec2(100.0, 520.0)).frame(); + panel.frame(); + panel.click_role("Preset:", Role::COMBO_BOX); + panel.key(egui::Key::ArrowDown, egui::Modifiers::NONE); + panel.key(egui::Key::Escape, egui::Modifiers::NONE); + assert_eq!(panel.app().ui.flattener_preview.options.balance, 12.0); + panel.click_role("Preset:", Role::COMBO_BOX); + panel.click("High Resolution"); + let expected = FlattenOptions::preset("high").unwrap(); + assert_eq!(panel.app().ui.flattener_preview.options, expected); + panel.app().run("select.all", json!({})).unwrap(); + panel.app().run("transparency.set", json!({"opacity": 100})).unwrap(); + assert!(stale(&panel.app()), "the live document changed"); + panel.click("Refresh"); + assert!(!stale(&panel.app()), "Refresh takes a new snapshot"); + let well = panel.rect("Flattener Preview"); + panel.click_at(well.center()); + assert!(!panel.app().flattener_preview.view.fit, "the compact preview still zooms"); + } + /// The panel in a fixture, and the preview pane's bounds. fn shown_pane() -> (std::rc::Rc>, craft::ui::testing::Fixture, egui::Rect) { let app = std::rc::Rc::new(std::cell::RefCell::new(app())); From bd619b9222b6b52b463e529497f651bab3124229 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 26 Nov 2026 13:22:48 -0800 Subject: [PATCH 148/151] Bind Document Setup actions to their source document --- crates/ui-egui/src/app.rs | 1 + crates/ui-egui/src/dialogs/document_setup.rs | 63 ++++++++++++++++++-- crates/ui-egui/src/lib.rs | 2 + 3 files changed, 62 insertions(+), 4 deletions(-) diff --git a/crates/ui-egui/src/app.rs b/crates/ui-egui/src/app.rs index 14329e8f0f..6ed9a2d818 100644 --- a/crates/ui-egui/src/app.rs +++ b/crates/ui-egui/src/app.rs @@ -234,6 +234,7 @@ impl VectorcraftApp { told: Default::default(), missing_font_edit_token: None, held: Default::default(), + document_setup_source: None, edit_scopes: Default::default(), command_dialog: Default::default(), effect_dialogs: Default::default(), diff --git a/crates/ui-egui/src/dialogs/document_setup.rs b/crates/ui-egui/src/dialogs/document_setup.rs index de5cac3c02..c3aa0ef099 100644 --- a/crates/ui-egui/src/dialogs/document_setup.rs +++ b/crates/ui-egui/src/dialogs/document_setup.rs @@ -73,7 +73,7 @@ pub fn open(app: &mut VectorcraftApp) -> Result { fields["rgbProfile"] = json!(rgb.unwrap_or_else(|| WORKING_RGB.into())); fields["cmykProfile"] = json!(cmyk.unwrap_or_else(|| WORKING_CMYK.into())); fields["convertColors"] = json!(true); - let (mode, setup) = (st.doc.color_mode, st.doc.setup.clone()); + let (source, mode, setup) = (st.uid, st.doc.color_mode, st.doc.setup.clone()); let Value::Object(map) = fields else { return Err("document.setup reported no settings".into()) }; let presets: Vec = app.session.flattener_presets().into_iter().map(|p| p.name).collect(); let display = app.display_profile.transform(app.session.prefs.monitor_profile_display); @@ -82,6 +82,7 @@ pub fn open(app: &mut VectorcraftApp) -> Result { PropertiesDialog::new(KIND, tl!("Document Setup"), tabs.clone(), values) }); super::host::open_held(app, dialog, |app, fields| confirm(app, fields).map(|_| ())).ok_or("no window to show the dialog in")?; + app.document_setup_source = Some(source); Ok(Value::Null) } @@ -185,6 +186,9 @@ fn color_commands(app: &VectorcraftApp, fields: &Map) -> Result Result { + if app.session.active().is_none_or(|st| Some(st.uid) != app.document_setup_source) { + return Err(tl!("Document Setup can only change the document where it was opened.").to_owned()); + } let map = json_map(fields); let params = nest(map.iter().filter(|(k, _)| !is_ui_only(k)).map(|(k, v)| (k.clone(), v.clone())).collect()); let color = color_commands(app, &map)?; @@ -220,9 +224,12 @@ fn short_of_bleed_note(app: &VectorcraftApp, before: [f64; 4]) -> Option pub(crate) fn pump(app: &mut VectorcraftApp, ctx: &egui::Context) { let Some(dialogs) = app.dialogs() else { return }; let id = dialog_id(KIND); - let edit = dialogs.with(|host| { - host.get_by_id::(id).filter(|d| d.fields().bool("editArtboards") == Some(true)).map(|d| d.fields().clone()) - }); + let Some(edit) = dialogs.with(|host| { + host.get_by_id::(id).map(|d| (d.fields().bool("editArtboards") == Some(true)).then(|| d.fields().clone())) + }) else { + app.document_setup_source = None; + return; + }; if let Some(fields) = edit { match confirm(app, &fields) { Ok(_) => { @@ -645,6 +652,54 @@ mod tests { app.session.active().unwrap().history.undo.len() } + fn check_source_document(edit_artboards: bool) { + let (mut app, ctx) = new_app(); + let source = app.session.active().unwrap().uid; + app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); + let destination = app.session.active().unwrap().uid; + app.run("document.activate", json!({"index": 0})).unwrap(); + app.run("file.documentSetup", json!({})).unwrap(); + set(&app, &ctx, "bleed", json!([9, 9, 9, 9])); + set(&app, &ctx, "colorMode", json!("cmyk")); + + let apply = |app: &mut VectorcraftApp| { + if edit_artboards { + set(app, &ctx, "editArtboards", json!(true)); + super::pump(app, &ctx); + !is_open(app) + } else { + press_ok(app, &ctx) + } + }; + app.run("document.activate", json!({"index": 1})).unwrap(); + let undo = undo_steps(&app); + let accepted = apply(&mut app); + let st = app.session.active().unwrap(); + assert_eq!(st.uid, destination); + assert_eq!((st.doc.setup.bleed, st.doc.color_mode), ([0.0; 4], ColorMode::Rgb), "the other document keeps its settings"); + assert_eq!(undo_steps(&app), undo); + assert_eq!(app.session.tool_id(), "selection"); + assert!(!accepted && is_open(&app)); + + app.run("document.activate", json!({"index": 0})).unwrap(); + assert!(apply(&mut app)); + let st = app.session.active().unwrap(); + assert_eq!(st.uid, source); + assert_eq!((st.doc.setup.bleed, st.doc.color_mode, undo_steps(&app)), ([9.0; 4], ColorMode::Cmyk, 1)); + assert_eq!(app.session.tool_id(), if edit_artboards { "artboard" } else { "selection" }); + assert!(!is_open(&app)); + } + + #[test] + fn source_document_is_required_to_confirm_document_setup() { + check_source_document(false); + } + + #[test] + fn source_document_is_required_to_edit_artboards_from_document_setup() { + check_source_document(true); + } + #[test] fn edit_artboards_applies_settings_and_closes_the_dialog() { let (mut app, ctx) = setup_open(); diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 6078ca0c07..412377ce61 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -270,6 +270,8 @@ pub struct VectorcraftApp { pub(crate) missing_font_edit_token: Option, /// The hosted dialogs whose OK the app answers, one record each. pub(crate) held: dialogs::host::Held, + /// The document whose settings the open Document Setup dialog edits. + pub(crate) document_setup_source: Option, /// The undo step each value gesture in progress edits under: a scrub or a slider drag is one /// step however many values it sets. pub(crate) edit_scopes: HashMap, From 4f8a7d22d9b5d93b838e9c5c5f2b12e27d62f5c9 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 26 Nov 2026 13:29:16 -0800 Subject: [PATCH 149/151] Keep Layer Options changes in their source document --- crates/ui-egui/src/dialogs/layer_options.rs | 62 +++++++++++++++++++-- 1 file changed, 56 insertions(+), 6 deletions(-) diff --git a/crates/ui-egui/src/dialogs/layer_options.rs b/crates/ui-egui/src/dialogs/layer_options.rs index 3ed57d9471..944051cf7d 100644 --- a/crates/ui-egui/src/dialogs/layer_options.rs +++ b/crates/ui-egui/src/dialogs/layer_options.rs @@ -249,8 +249,9 @@ fn fields_of(n: &Node, xml_id: bool) -> LayerOptionsValue { /// Opens the dialog on `value`. fn open_value(app: &mut VectorcraftApp, value: LayerOptionsValue) -> Result { + let document = app.session.active().ok_or("no document open")?.uid; let dialogs = app.dialogs().ok_or("no window")?; - dialogs.with(|host| host.open(LayerOptionsDialog::new(value))); + dialogs.with(|host| host.open(LayerOptionsDialog::new(document, value))); Ok(Value::Null) } @@ -410,6 +411,7 @@ pub(crate) fn params(v: &LayerOptionsValue) -> (&'static str, Value) { /// the dialog open with the reason under its rows. pub(crate) struct LayerOptionsDialog { id: DialogId, + document: u64, open: bool, value: LayerOptionsValue, held: HeldAnswer, @@ -421,8 +423,8 @@ pub(crate) struct LayerOptionsDialog { impl LayerOptionsDialog { /// The dialog over `value`. - fn new(value: LayerOptionsValue) -> Self { - LayerOptionsDialog { id: dialog_id(KEY), open: true, value, held: HeldAnswer::new(), refused_at: None, color_request: None } + fn new(document: u64, value: LayerOptionsValue) -> Self { + LayerOptionsDialog { id: dialog_id(KEY), document, open: true, value, held: HeldAnswer::new(), refused_at: None, color_request: None } } /// The OK filed by the user, once. @@ -571,7 +573,12 @@ pub(crate) fn pump(app: &mut VectorcraftApp, ctx: &egui::Context) { let Some(dialogs) = app.dialogs() else { return }; // The closed dialog's answer was run when OK was filed. let _ = dialogs.with(|host| host.take::()); - let Some(value) = dialogs.with(|host| host.get_mut::().and_then(LayerOptionsDialog::take_filed)) else { return }; + let Some((document, value)) = dialogs.with(|host| { + let dialog = host.get_mut::()?; + Some((dialog.document, dialog.take_filed()?)) + }) else { + return; + }; let (cmd, p) = params(&value); let sublayer = match cmd { "layer.new" => Some(false), @@ -579,8 +586,9 @@ pub(crate) fn pump(app: &mut VectorcraftApp, ctx: &egui::Context) { _ => None, }; // Isolation mode can start while the dialog is open. - let answer = match sublayer { - Some(sublayer) if app.session.active().is_some_and(|st| crate::panels::layers::new_layer_unlisted(st, sublayer, false)) => { + let answer = match app.session.active().filter(|st| st.uid == document) { + None => Err(Label::from(tl!("Layer Options can only change the document it was opened for."))), + Some(st) if sublayer.is_some_and(|sublayer| crate::panels::layers::new_layer_unlisted(st, sublayer, false)) => { Err(Label::from("exit isolation mode first")) } _ => { @@ -681,6 +689,48 @@ mod tests { assert_eq!(app.session.doc().unwrap().history.undo.len(), undo + 1); } + #[test] + fn layer_options_and_new_layers_follow_their_document() { + for (command, arguments) in [("ui.layerOptions", json!({})), ("ui.newLayer", json!({})), ("ui.newLayer", json!({"sublayer": true}))] { + let mut app = app(); + let source_id = app.session.active().unwrap().doc.layers[0].id; + app.run("file.new", json!({"width": 160, "height": 160})).unwrap(); + let destination_id = app.session.active().unwrap().doc.layers[0].id; + assert_eq!(destination_id, source_id, "the two documents reuse a layer ID"); + let activate = |app: &mut VectorcraftApp, index| app.run("document.activate", json!({"index": index})).unwrap(); + activate(&mut app, 0); + app.run(command, arguments).unwrap(); + set(&mut app, "name", json!("Source Draft")); + let ctx = app.ui_ctx.clone().unwrap(); + let dialog = open_id(&app); + app.dialogs().unwrap().with(|host| host.confirm_by_id(&ctx, dialog)); + + let layers = |app: &VectorcraftApp| { + let mut names = vec![]; + app.session.active().unwrap().doc.walk(|node| { + if node.is_layer() { + names.push(node.display_name()); + } + }); + names + }; + activate(&mut app, 1); + let before = layers(&app); + let b_undo = app.session.active().unwrap().history.undo.len(); + pump(&mut app, &ctx); + assert_eq!(layers(&app), before, "the destination's layers stay unchanged for {command}"); + assert_eq!(app.session.active().unwrap().history.undo.len(), b_undo); + assert!(matches!(app.dialogs().unwrap().with(|host| host.held_state(dialog)), Some(HeldOk::Refused(_)))); + + activate(&mut app, 0); + let a_undo = app.session.active().unwrap().history.undo.len(); + ok(&mut app); + assert!(!app.any_dialog_open()); + assert!(layers(&app).iter().any(|name| name == "Source Draft")); + assert_eq!(app.session.active().unwrap().history.undo.len(), a_undo + 1); + } + } + /// Two layers with different options, the first plain and the second green, locked, in /// outline view and dimmed to 30%. fn two_layers(app: &mut VectorcraftApp) -> (NodeId, NodeId) { From 1573e976e0677905663fc8f29bc715754d8edcd4 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 26 Nov 2026 13:40:13 -0800 Subject: [PATCH 150/151] Keep saved Selection and View edits with their document --- crates/ui-egui/src/dialogs/saved_names.rs | 79 +++++++++++++++++++++-- 1 file changed, 72 insertions(+), 7 deletions(-) diff --git a/crates/ui-egui/src/dialogs/saved_names.rs b/crates/ui-egui/src/dialogs/saved_names.rs index d14a41fb74..0bbf1e89ea 100644 --- a/crates/ui-egui/src/dialogs/saved_names.rs +++ b/crates/ui-egui/src/dialogs/saved_names.rs @@ -137,6 +137,7 @@ impl ItemSource for Shown<'_> {} /// The saved-names dialog of one kind. pub(crate) struct SavedNamesDialog { id: DialogId, + document: u64, names: SavedNames, draft: NamesDraft, /// The picked row, by its index in the draft; one at most. @@ -147,10 +148,10 @@ pub(crate) struct SavedNamesDialog { impl SavedNamesDialog { /// The dialog over `list`, with the first name picked. - fn new(names: SavedNames, list: Vec) -> Self { + fn new(document: u64, names: SavedNames, list: Vec) -> Self { let selection = if list.is_empty() { Selection::default() } else { Selection::single(0) }; let rows = list.into_iter().map(|name| NameRow { orig: name.clone(), name, deleted: false }).collect(); - SavedNamesDialog { id: id_of(names.kind), names, draft: NamesDraft { rows }, selection, held: HeldAnswer::new() } + SavedNamesDialog { id: id_of(names.kind), document, names, draft: NamesDraft { rows }, selection, held: HeldAnswer::new() } } /// OK as its button gives it: with nothing edited the dialog closes at once (`Some`); with edits they wait for @@ -326,8 +327,9 @@ impl StackDialog for SavedNamesDialog { /// Opens the dialog of `names` on `list`, the saved names in their order (the first `names.max` of them). pub(crate) fn open(app: &mut VectorcraftApp, names: SavedNames, mut list: Vec) -> Result<(), String> { list.truncate(names.max); + let document = app.session.active().ok_or("no document open")?.uid; let dialogs = app.dialogs().ok_or("no window")?; - dialogs.with(|host| host.open(SavedNamesDialog::new(names, list))); + dialogs.with(|host| host.open(SavedNamesDialog::new(document, names, list))); Ok(()) } @@ -335,18 +337,22 @@ pub(crate) fn open(app: &mut VectorcraftApp, names: SavedNames, mut list: Vec)> = dialogs.with(|host| { + let filed: Vec<_> = dialogs.with(|host| { host.open_dialogs() .into_iter() .filter_map(|open| { let dialog = host.get_mut_by_id::(open.id)?; let edits = dialog.held.take()?; - Some((open.id, dialog.names.command, edits)) + Some((open.id, dialog.document, dialog.names.command, edits)) }) .collect() }); - for (id, command, edits) in filed { - let outcome = app.run(command, json!({ "edits": edits })); + for (id, document, command, edits) in filed { + let outcome = if app.session.active().is_some_and(|active| active.uid == document) { + app.run(command, json!({ "edits": edits })) + } else { + Err(tl!("Saved names can only be edited in the document this dialog was opened for.").to_owned()) + }; if let Err(reason) = &outcome { app.status(reason.clone()); } @@ -357,3 +363,62 @@ pub(crate) fn pump(app: &mut VectorcraftApp, _ctx: &egui::Context) { }); } } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn saved_names_edits_stay_with_their_document() { + for is_view in [false, true] { + let mut app = crate::testing::windowed(VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default())); + for size in [100, 200] { + app.run("file.new", json!({"width": size, "height": size})).unwrap(); + app.run("shape.rectangle", json!({"x": 0, "y": 0, "width": 10, "height": 10})).unwrap(); + for name in ["Shared", "Spare"] { + app.run(if is_view { "view.saved.new" } else { "select.save" }, json!({"name": name})).unwrap(); + } + } + let names = |app: &mut VectorcraftApp| { + if is_view { + let views = &app.session.active().unwrap().doc.views; + json!(views.iter().map(|view| &view.name).collect::>()) + } else { + app.run("select.savedList", json!({})).unwrap() + } + }; + let activate = |app: &mut VectorcraftApp, index| app.run("document.activate", json!({"index": index})).unwrap(); + activate(&mut app, 0); + let kind = if is_view { + crate::dialogs::edit_views::open(&mut app).unwrap(); + crate::dialogs::edit_views::KIND + } else { + crate::dialogs::edit_selection::open(&mut app).unwrap(); + crate::dialogs::edit_selection::KIND + }; + let id = id_of(kind); + let ctx = app.ui_ctx.clone().unwrap(); + let host = app.dialogs().unwrap(); + host.with(|h| { + h.set_json_field(&ctx, id, "name0", json!("Revised")).unwrap(); + h.set_json_field(&ctx, id, "deleted1", json!(true)).unwrap(); + h.confirm_by_id(&ctx, id); + }); + + activate(&mut app, 1); + let b_undo = app.session.active().unwrap().history.undo.len(); + pump(&mut app, &ctx); + assert_eq!(names(&mut app), json!(["Shared", "Spare"]), "the destination's saved names stay unchanged for {kind}"); + assert_eq!(app.session.active().unwrap().history.undo.len(), b_undo); + assert!(matches!(host.with(|h| h.held_state(id)), Some(HeldOk::Refused(_)))); + + activate(&mut app, 0); + let a_undo = app.session.active().unwrap().history.undo.len(); + host.with(|h| h.confirm_by_id(&ctx, id)); + pump(&mut app, &ctx); + assert!(matches!(host.with(|h| h.held_state(id)), Some(HeldOk::Accepted))); + assert_eq!(names(&mut app), json!(["Revised"])); + assert_eq!(app.session.active().unwrap().history.undo.len(), a_undo + 1); + } + } +} From b458d505953a951799a4f509d518e4532e26a1e9 Mon Sep 17 00:00:00 2001 From: bflatastic Date: Fri, 27 Nov 2026 05:52:11 +0700 Subject: [PATCH 151/151] Properties: the stroke-profile check asks tool_paints, which replaced bucket_paints --- crates/ui-egui/src/panels/properties/appearance_section.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/crates/ui-egui/src/panels/properties/appearance_section.rs b/crates/ui-egui/src/panels/properties/appearance_section.rs index cd71a0f035..b3266b032d 100644 --- a/crates/ui-egui/src/panels/properties/appearance_section.rs +++ b/crates/ui-egui/src/panels/properties/appearance_section.rs @@ -100,9 +100,9 @@ fn effect_delete(app: &mut VectorcraftApp, ui: &mut Ui, id: NodeId, effects: &[( /// Whether a stroke that `stroke.set` edits has a width profile /// ([`vectorcraft_engine::Session::edited_strokes_profiled`]), cached per document revision and /// active Appearance row in `PropertiesUi::edited_profiled`. False while the Type tool edits text or -/// the Live Paint Bucket is active, when the list edits the stroke the panel shows. +/// a tool paints the stroke ([`vectorcraft_engine::Session::tool_paints`]), when the list edits the stroke the panel shows. fn edited_strokes_profiled(app: &mut VectorcraftApp) -> bool { - if panels::character::text_editing(app).is_some() || app.session.bucket_paints() { + if panels::character::text_editing(app).is_some() || app.session.tool_paints(true) { return false; } let Some(st) = app.session.active() else { return false };