diff --git a/Cargo.lock b/Cargo.lock index 88a9abca04..b77485ae02 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -975,12 +975,12 @@ source = "git+https://github.com/storytold/craft-libs?rev=9be9a63782298ab59cd9b7 [[package]] name = "craft-fonts-build" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb#9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb" +source = "git+https://github.com/storytold/craft-libs?rev=bb8320f5fa5d20fa78a026d0de06fe4e2f08a099#bb8320f5fa5d20fa78a026d0de06fe4e2f08a099" [[package]] name = "craft-i18n" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb#9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb" +source = "git+https://github.com/storytold/craft-libs?rev=bb8320f5fa5d20fa78a026d0de06fe4e2f08a099#bb8320f5fa5d20fa78a026d0de06fe4e2f08a099" dependencies = [ "fixed_decimal", "icu_decimal", @@ -1049,7 +1049,7 @@ dependencies = [ [[package]] name = "craft-ui" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb#9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb" +source = "git+https://github.com/storytold/craft-libs?rev=bb8320f5fa5d20fa78a026d0de06fe4e2f08a099#bb8320f5fa5d20fa78a026d0de06fe4e2f08a099" dependencies = [ "craft-fonts-build", "craft-i18n", @@ -6652,6 +6652,8 @@ dependencies = [ "kurbo 0.13.1", "log", "md-5", + "objc2-core-foundation", + "objc2-core-graphics", "roxmltree 0.21.2", "serde", "serde_json", diff --git a/Cargo.toml b/Cargo.toml index 2c0bf38ec9..9b4b99c92d 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -14,7 +14,7 @@ repository = "https://github.com/storytold/vectorcraft" craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb", default-features = false, features = ["interpret", "write"] } craft-print = { git = "https://github.com/storytold/craft-libs", rev = "9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb" } craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb" } -craft-ui = { git = "https://github.com/storytold/craft-libs", rev = "9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb", features = ["serde"] } +craft-ui = { git = "https://github.com/storytold/craft-libs", rev = "bb8320f5fa5d20fa78a026d0de06fe4e2f08a099", features = ["serde"] } craft-keymap = { git = "https://github.com/storytold/craft-libs", rev = "9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb" } craft-proof = { git = "https://github.com/storytold/craft-libs", rev = "9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb" } # Decides who draws the window frame (desktop vs. app) so the suite shares one native titlebar per diff --git a/apps/vectorcraft-cli/tests/it/main.rs b/apps/vectorcraft-cli/tests/it/main.rs index 6918ea19b6..07e5a3a70d 100644 --- a/apps/vectorcraft-cli/tests/it/main.rs +++ b/apps/vectorcraft-cli/tests/it/main.rs @@ -5,3 +5,4 @@ mod cli; mod fileio; mod mcp_e2e; +mod script; diff --git a/apps/vectorcraft-cli/tests/it/script.rs b/apps/vectorcraft-cli/tests/it/script.rs new file mode 100644 index 0000000000..d68716f7b3 --- /dev/null +++ b/apps/vectorcraft-cli/tests/it/script.rs @@ -0,0 +1,39 @@ +use std::process::Command; + +use serde_json::{Value, json}; + +const BIN: &str = env!("CARGO_BIN_EXE_vectorcraft-cli"); + +/// `run` with `script.run` after `file.new`, with `params`. +fn run_script(params: &Value) -> std::process::Output { + Command::new(BIN).args(["run", "--cmd", "file.new", "--cmd", "script.run", "--params", ¶ms.to_string()]).output().unwrap() +} + +/// `run` runs a script headless: the reply holds the report, with what the script logged and the +/// documents it changed. +#[test] +fn run_gives_the_report_of_a_script() { + let source = "vc.run('shape.rectangle', {x: 0, y: 0, width: 10, height: 10}); vc.log(vc.args.n * 2);"; + let out = run_script(&json!({"source": source, "name": "double.js", "args": {"n": 21}})); + assert!(out.status.success(), "{}", String::from_utf8_lossy(&out.stderr)); + let lines: Vec = String::from_utf8_lossy(&out.stdout).lines().map(|l| serde_json::from_str(l).unwrap()).collect(); + assert_eq!(lines.len(), 2, "{lines:?}"); + assert_eq!(lines[1]["command"], "script.run"); + let report = &lines[1]["result"]; + assert_eq!(report["ok"], true, "{report}"); + assert_eq!(report["name"], "double.js"); + assert_eq!(report["log"], json!([42]), "{report}"); + assert_eq!(report["changed"].as_array().map(Vec::len), Some(1), "{report}"); +} + +/// A script that throws fails its step with the script's message, and the steps before it ran. +#[test] +fn run_fails_the_step_of_a_script_that_throws() { + let out = run_script(&json!({"source": "vc.run('shape.rectangle', {x: 0, y: 0, width: 10, height: 10}); throw new Error('no margin given');"})); + assert!(!out.status.success()); + let stderr = String::from_utf8_lossy(&out.stderr); + assert!(stderr.contains("step 1 (script.run)") && stderr.contains("no margin given"), "{stderr}"); + let printed: Vec = String::from_utf8_lossy(&out.stdout).lines().map(|l| serde_json::from_str(l).unwrap()).collect(); + assert_eq!(printed.len(), 1, "only file.new printed: {printed:?}"); + assert_eq!(printed[0]["command"], "file.new"); +} diff --git a/apps/vectorcraft-web/Cargo.toml b/apps/vectorcraft-web/Cargo.toml index 6e4dbd7f00..eb35a110c7 100644 --- a/apps/vectorcraft-web/Cargo.toml +++ b/apps/vectorcraft-web/Cargo.toml @@ -26,7 +26,7 @@ log = { workspace = true } [target.'cfg(target_arch = "wasm32")'.dependencies] # `wgpu` pulls egui-wgpu's defaults: WebGPU plus the WebGL2 fallback. eframe = { workspace = true, features = ["default_fonts", "wgpu", "accesskit"] } -rfd = { workspace = true } +rfd = { workspace = true, features = ["file-handle-inner"] } wasm-bindgen = "0.2" serde_json = { workspace = true } wasm-bindgen-futures = "0.4" diff --git a/apps/vectorcraft-web/src/web.rs b/apps/vectorcraft-web/src/web.rs index 60682d6986..b4ca434d90 100644 --- a/apps/vectorcraft-web/src/web.rs +++ b/apps/vectorcraft-web/src/web.rs @@ -9,6 +9,9 @@ use vectorcraft_engine::Session; use vectorcraft_engine::cmd::clipboard::{FILE_HEAD, Flavour, PASTE_ORDER, file_flavour, is_address}; use vectorcraft_engine::cmd::fileio; use vectorcraft_engine::cmd::recovery::{self, Hold, RecoveryStore}; +use vectorcraft_engine::cmd::scripts::RUN_EXTS; +use vectorcraft_engine::script::MAX_SOURCE_BYTES; +use vectorcraft_ui_egui::dialogs::script_run::ScriptInbox; use vectorcraft_ui_egui::graphics::GraphicsLoss; use vectorcraft_ui_egui::i18n; use vectorcraft_ui_egui::place::{DropTarget, PlaceArrival, PlaceInbox}; @@ -47,6 +50,7 @@ struct Host { runner: eframe::WebRunner, inbox: Inbox, place_inbox: PlaceInbox, + script_inbox: ScriptInbox, drag: DragPos, pasted: Rc>, /// Pen and finger input read from the page's Pointer Events (`crate::pencil`). @@ -75,6 +79,7 @@ pub fn start() { runner: eframe::WebRunner::new(), inbox: Arc::default(), place_inbox: Arc::default(), + script_inbox: Arc::default(), drag: DragPos::default(), pasted: Rc::default(), pointers: SharedPointers::default(), @@ -120,7 +125,8 @@ async fn run(host: Host, canvas: web_sys::HtmlCanvasElement, moving: Option { // The old services asked the old context for frames. @@ -425,12 +431,35 @@ impl eframe::App for WebShell { } } -fn services(inbox: Inbox, place_inbox: PlaceInbox, ctx: egui::Context, locks: Option, stylus: StylusFeed) -> Services { +fn services( + inbox: Inbox, + place_inbox: PlaceInbox, + script_inbox: ScriptInbox, + ctx: egui::Context, + locks: Option, + stylus: StylusFeed, +) -> Services { let open_inbox = inbox.clone(); let picked = place_inbox.clone(); let place_ctx = ctx.clone(); let screen_color = eye_dropper(ctx.clone()); + let (script_picked, script_ctx) = (script_inbox.clone(), ctx.clone()); Services { + // File › Scripts › Other Script…: the picked file goes to the warning before it runs. + script_async: Some(Box::new(move || { + let inbox = script_picked.clone(); + let ctx = script_ctx.clone(); + wasm_bindgen_futures::spawn_local(async move { + let filter = vectorcraft_ui_egui::i18n::tr_ctx(vectorcraft_ui_egui::i18n::current(), "file-filter", "Scripts"); + let Some(file) = rfd::AsyncFileDialog::new().add_filter(filter, RUN_EXTS).pick_file().await else { + return; + }; + let bytes = if file.inner().size() > MAX_SOURCE_BYTES as f64 { None } else { Some(file.read().await) }; + inbox.lock().unwrap_or_else(|e| e.into_inner()).push((file.file_name(), bytes)); + ctx.request_repaint(); + }); + })), + script_inbox: Some(script_inbox), // File → Place…: the picked files go to the Place dialog. place_async: Some(Box::new(move || { let inbox = picked.clone(); diff --git a/crates/doc/src/appearance.rs b/crates/doc/src/appearance.rs index 3ac145fd22..2e19ad44a3 100644 --- a/crates/doc/src/appearance.rs +++ b/crates/doc/src/appearance.rs @@ -8,7 +8,6 @@ mod layers; mod profile; mod stroke_style; -pub(crate) use layers::HEAD_REACH; pub use layers::{Effect, FillLayer, StrokeGradientMode, StrokeLayer, stroke_paint_bounds}; pub use profile::{AngleProfile, PressureProfile, ProfilePreset, SavedProfile, WidthProfile}; pub use stroke_style::{ArrowAlign, Arrowhead, Dash, LineCap, LineJoin, StrokeAlign}; diff --git a/crates/doc/src/appearance/layers.rs b/crates/doc/src/appearance/layers.rs index 880f3490da..923275999b 100644 --- a/crates/doc/src/appearance/layers.rs +++ b/crates/doc/src/appearance/layers.rs @@ -139,10 +139,6 @@ impl StrokeGradientMode { } } -/// How far any arrowhead reaches from its tip, in units of its weight (the open arrow's arms are -/// cut square a little behind its 4 × 4 box). -pub(crate) const HEAD_REACH: f64 = 4.6; - fn ten() -> f64 { 10.0 } @@ -188,7 +184,8 @@ impl StrokeLayer { } } /// Weight of the start (`end == false`) or end arrowhead: stroke weight × its scale, at least - /// a quarter point. A head of weight `hw` fits a box about `4·hw` long and wide. + /// a quarter point. A head of weight `hw` fits a box about `4·hw` long and wide (see + /// [`Arrowhead::reach`] and [`Arrowhead::half_width`]). pub fn arrow_weight(&self, end: bool) -> f64 { let pct = if end { self.arrow_scale.1 } else { self.arrow_scale.0 }; (self.width * pct / 100.0).max(0.25) @@ -197,7 +194,7 @@ impl StrokeLayer { /// without one): the head's diagonal, or with [`ArrowAlign::Extend`] its length, plus the cap. pub fn head_reach(&self, end: bool) -> f64 { let head = if end { self.end_arrow } else { self.start_arrow }; - head.map_or(0.0, |_| HEAD_REACH * self.arrow_weight(end) + self.width / 2.0) + head.map_or(0.0, |k| k.reach() * self.arrow_weight(end) + self.width / 2.0) } /// How far the arrowheads can reach from the path's end points (0 without heads). pub fn arrow_reach(&self) -> f64 { diff --git a/crates/doc/src/appearance/stroke_style.rs b/crates/doc/src/appearance/stroke_style.rs index acd4d81890..46a0c30c33 100644 --- a/crates/doc/src/appearance/stroke_style.rs +++ b/crates/doc/src/appearance/stroke_style.rs @@ -49,6 +49,10 @@ impl Dash { } } +/// How far the arrowheads drawn in the 4 × 4 box reach from their tip, in units of their weight +/// (the open arrow's arms are cut square a little behind the box). +const HEAD_REACH: f64 = 4.6; + /// An arrowhead shape. Saved by variant name: new shapes are appended, never renamed or reordered. #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)] pub enum Arrowhead { @@ -94,13 +98,18 @@ pub enum Arrowhead { Kite, TriangleBar, Oval, + /// Two arms of the head's weight (the line's weight at 100 % scale, for lines of 0.25 pt or + /// more) meeting at right angles in a sharp tip, cut square at their ends. Twice as wide as + /// the other heads. + LineArrow, } impl Arrowhead { /// Every arrowhead, in menu order (arrows, then outlined shapes, then bars and marks). - pub const ALL: [Arrowhead; 40] = [ + pub const ALL: [Arrowhead; 41] = [ Arrowhead::Arrow, Arrowhead::ArrowOpen, + Arrowhead::LineArrow, Arrowhead::Barbed, Arrowhead::Concave, Arrowhead::DoubleArrow, @@ -141,6 +150,22 @@ impl Arrowhead { Arrowhead::Fork, ]; + /// How far any part of the head can be from its tip, in units of its weight. + pub fn reach(self) -> f64 { + match self { + // Its farthest corners are 4 + ½√2 back and 4 − ½√2 out. + Arrowhead::LineArrow => 5.75, + _ => HEAD_REACH, + } + } + /// How far the head spreads either side of its line, in units of its weight. + pub fn half_width(self) -> f64 { + match self { + Arrowhead::LineArrow => 4.0, + _ => 2.0, + } + } + /// The name the arrowhead menus show. pub fn label(self) -> &'static str { match self { @@ -184,6 +209,7 @@ impl Arrowhead { Arrowhead::Kite => "Kite", Arrowhead::TriangleBar => "Triangle to Bar", Arrowhead::Oval => "Oval", + Arrowhead::LineArrow => "Line Arrow", } } } diff --git a/crates/doc/src/appearance/tests.rs b/crates/doc/src/appearance/tests.rs index c297b34759..0a1b3e1a5d 100644 --- a/crates/doc/src/appearance/tests.rs +++ b/crates/doc/src/appearance/tests.rs @@ -219,7 +219,7 @@ fn profile_presets_round_trip_their_ids() { #[test] fn arrowhead_names_are_stable_and_every_one_is_listed_once() { // Saved files store these names: they may only ever be appended to. - const SAVED: [&str; 40] = [ + const SAVED: [&str; 41] = [ "Triangle", "TriangleOpen", "Circle", @@ -260,6 +260,7 @@ fn arrowhead_names_are_stable_and_every_one_is_listed_once() { "Kite", "TriangleBar", "Oval", + "LineArrow", ]; for name in SAVED { let a: Arrowhead = serde_json::from_value(serde_json::json!(name)).unwrap(); @@ -293,9 +294,15 @@ fn outset_covers_arrowheads() { st.arrow_scale = (100.0, 200.0); assert_eq!(st.arrow_weight(false), 4.0); assert_eq!(st.arrow_weight(true), 8.0); - assert_eq!((st.head_reach(false), st.head_reach(true)), (0.0, HEAD_REACH * 8.0 + 2.0)); + let reach = Arrowhead::Triangle.reach(); + assert_eq!((st.head_reach(false), st.head_reach(true)), (0.0, reach * 8.0 + 2.0)); // A 32 pt head whose tip sits up to its length (plus the cap) past the end point. - assert_eq!(a.outset(), HEAD_REACH * 8.0 + 2.0); + assert_eq!(a.outset(), reach * 8.0 + 2.0); + // The line arrow's arms spread twice as wide, so it reaches further from its tip. + a.stroke_mut().unwrap().end_arrow = Some(Arrowhead::LineArrow); + assert!(Arrowhead::LineArrow.reach() > reach); + assert_eq!(a.outset(), Arrowhead::LineArrow.reach() * 8.0 + 2.0); + a.stroke_mut().unwrap().end_arrow = Some(Arrowhead::Triangle); a.stroke_mut().unwrap().width = 0.01; assert_eq!(a.stroke().unwrap().arrow_weight(true), 0.25, "heads keep a minimum size"); } diff --git a/crates/doc/src/document.rs b/crates/doc/src/document.rs index ebd27fd87f..2a2f8a8d7a 100644 --- a/crates/doc/src/document.rs +++ b/crates/doc/src/document.rs @@ -276,6 +276,11 @@ impl Document { self.next_id } + /// Makes the next id at least `id`, so ids below it are not given out again. + pub fn raise_next_id(&mut self, id: u64) { + self.next_id = self.next_id.max(id); + } + /// Ensure `next_id` is above every id in the tree (after deserializing foreign data). pub fn fix_next_id(&mut self) { // Ids from [`MAX_NEXT_ID`] up (a damaged or hand-made file: #1718) are left out, as is a diff --git a/crates/doc/src/document_ext.rs b/crates/doc/src/document_ext.rs index c40dcf9f21..ebb2fc44eb 100644 --- a/crates/doc/src/document_ext.rs +++ b/crates/doc/src/document_ext.rs @@ -123,18 +123,33 @@ impl Document { std::borrow::Cow::Owned(d) } - /// Does `wants` hold for a node anywhere in the document's art: the layers, symbol definitions, - /// graph designs, pattern swatches (the one being edited included) and their opacity masks? - pub fn any_node(&self, wants: impl Fn(&Node) -> bool) -> bool { - let roots = self - .layers + /// The roots of every tree of the document's art: the layers, symbol definitions, graph designs, + /// pattern swatches and the original of the pattern being edited. Opacity masks hang off nodes + /// in these trees. + pub fn art_roots(&self) -> impl Iterator> { + self.layers .iter() .chain(self.symbols.iter().map(|s| &s.art)) .chain(self.graph_designs.iter().map(|g| &g.art)) .chain(self.patterns.iter().flat_map(|p| p.art.iter())) - .chain(self.pattern_edit.iter().filter_map(|pe| pe.original.as_ref()).flat_map(|p| p.art.iter())); + .chain(self.pattern_edit.iter().filter_map(|pe| pe.original.as_ref()).flat_map(|p| p.art.iter())) + } + + /// [`Self::art_roots`], to change. + pub fn art_roots_mut(&mut self) -> impl Iterator> { + 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())) + } + + /// Does `wants` hold for a node anywhere in the document's art ([`Self::art_roots`]) or its + /// opacity masks? + pub fn any_node(&self, wants: impl Fn(&Node) -> bool) -> bool { let mut any = false; - for root in roots { + for root in self.art_roots() { crate::swatches::walk_with_masks(root, &mut |n| any |= wants(n)); } any @@ -144,14 +159,7 @@ impl Document { /// [`Self::any_node`] looks). Only the trees that hold such a node are copied out of the art /// they share. pub fn edit_nodes_where(&mut self, wants: impl Fn(&Node) -> bool, mut f: impl FnMut(&mut Node)) { - 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 { + for root in self.art_roots_mut() { edit_branches_where(root, &wants, &mut f); } } diff --git a/crates/doc/src/reach.rs b/crates/doc/src/reach.rs index 99fb6b03d9..f6b9a4d013 100644 --- a/crates/doc/src/reach.rs +++ b/crates/doc/src/reach.rs @@ -7,7 +7,6 @@ use vectorcraft_geom::hit::fill_contains; use vectorcraft_geom::kurbo::{ParamCurveArclen, ParamCurveExtrema, ParamCurveNearest}; use vectorcraft_geom::{BezPath, FillRule, ParamCurve, PathSeg, Point, Rect, Shape, Vec2}; -use crate::appearance::HEAD_REACH; use crate::{Appearance, ArrowAlign, Dash, LineCap, LineJoin, StrokeAlign, StrokeLayer, WidthProfile}; /// Arc-length accuracy for placing a point along a profile (document points). @@ -386,18 +385,19 @@ impl StrokeLayer { } /// Is `p` within `tol` of where the start (`end == false`) or end arrowhead at `at` (the path - /// leaving along `out`) can paint? Heads are at most about 4.6 weights long and 4 wide. With + /// leaving along `out`) can paint? A head reaches [`crate::Arrowhead::reach`] weights from its tip and + /// [`crate::Arrowhead::half_width`] either side of its line (4.6 and 2 for most). With /// [`ArrowAlign::Extend`] a head points along `out` with its tip up to its length (or the cap) /// past the end; with [`ArrowAlign::Tip`] its tip is on the end and it lies back along the /// chord the path bends through under it, so anywhere within its length of the end. fn head_contains(&self, at: Point, out: Vec2, end: bool, p: Point, tol: f64) -> bool { - let hw = self.arrow_weight(end); - let v = p - at; + let Some(kind) = (if end { self.end_arrow } else { self.start_arrow }) else { return false }; + let (hw, v) = (self.arrow_weight(end), p - at); match self.arrow_align { - ArrowAlign::Tip => v.hypot() <= HEAD_REACH * hw + tol, + ArrowAlign::Tip => v.hypot() <= kind.reach() * hw + tol, ArrowAlign::Extend => { let along = v.dot(out); - v.cross(out).abs() <= 2.0 * hw + tol && along <= 4.0 * hw + self.width / 2.0 + tol && along >= -HEAD_REACH * hw - tol + v.cross(out).abs() <= kind.half_width() * hw + tol && along <= 4.0 * hw + self.width / 2.0 + tol && along >= -kind.reach() * hw - tol } } } diff --git a/crates/doc/src/style_libs.rs b/crates/doc/src/style_libs.rs index 6eda3acef1..90424d5bc2 100644 --- a/crates/doc/src/style_libs.rs +++ b/crates/doc/src/style_libs.rs @@ -158,6 +158,7 @@ pub const STYLE_LIBRARIES: &[BuiltinStyleLibrary] = &[ BuiltinStyleLibrary { id: "gradient-finishes", name: "Gradient Finishes", make: gradient_finishes }, BuiltinStyleLibrary { id: "shape-effects", name: "Shape Effects", make: shape_effects }, BuiltinStyleLibrary { id: "blends-transparency", name: "Blends and Transparency", make: blends_transparency }, + BuiltinStyleLibrary { id: "game-hud", name: "Game HUD", make: game_hud }, ]; /// Built-in library `id`, made once. @@ -453,6 +454,34 @@ fn blends_transparency() -> Vec { ] } +/// Game HUD: fills and glows for health, mana, damage and quest chrome (original arcade/HUD look). +fn game_hud() -> Vec { + vec![ + style("Health Fill", vec![F(fill("#e74c3c")), S(stroke("#5c1a1a", 1.25))], vec![]), + style( + "Mana Glow", + vec![F(fill("#3498db"))], + vec![fx("stylize.outerGlow", json!({"mode": "normal", "opacity": 85.0, "blur": 7.0, "color": "#5dade2"}))], + ), + style( + "Damage Flash", + vec![F(fill("#ff6b35"))], + vec![fx("stylize.innerGlow", json!({"mode": "screen", "opacity": 80.0, "blur": 8.0, "color": "#ffe66d", "source": "edge"}))], + ), + style("Quest Outline", vec![F(fill("#f7f3e8")), S(round("#2c3e50", 3.0))], vec![]), + style( + "Coin Shine", + vec![F(fill("#f1c40f")), S(stroke("#b7950b", 1.5))], + vec![fx("stylize.dropShadow", json!({"mode": "multiply", "opacity": 40.0, "x": 2.0, "y": 3.0, "blur": 4.0, "color": "#1d1b2a"}))], + ), + style( + "Boss Alert", + vec![F(fill("#1a1a2e")), S(round("#e94560", 2.5))], + vec![fx("stylize.outerGlow", json!({"mode": "normal", "opacity": 75.0, "blur": 6.0, "color": "#e94560"}))], + ), + ] +} + #[cfg(test)] mod tests { use super::*; @@ -475,6 +504,10 @@ mod tests { } assert!(Arc::ptr_eq(&builtin_style_library("hand-drawn").unwrap(), &builtin_style_library("hand-drawn").unwrap()), "made once"); assert!(builtin_style_library("nope").is_none()); + let game = builtin_style_library("game-hud").unwrap(); + assert_eq!(game.name, "Game HUD"); + let names: Vec<&str> = game.styles.iter().map(|g| g.name.as_str()).collect(); + assert_eq!(names, ["Health Fill", "Mana Glow", "Damage Flash", "Quest Outline", "Coin Shine", "Boss Alert"]); } #[test] diff --git a/crates/doc/src/text/object.rs b/crates/doc/src/text/object.rs index 12bc7ec89a..bb1fa0eb2c 100644 --- a/crates/doc/src/text/object.rs +++ b/crates/doc/src/text/object.rs @@ -367,6 +367,24 @@ impl TextObject { pub fn move_path_anchors(&mut self, refs: &[(usize, usize)], d: Vec2) -> bool { matches!(self.kind, TextKind::OnPath { .. }) && self.reshape_local(|path, to_text| move_anchors(path, to_text, refs, d)) } + /// Move the out (`out`) or in direction handle of anchor `ai` of subpath `si` of type on a + /// path's path to `pos` in document space, as a path's anchor takes it + /// ([`vectorcraft_geom::Anchor::set_handle`]; `independent`: that side only, the anchor a + /// corner): a Direct Selection drag of a handle (#3565). The handle is set in document space, + /// so a smooth anchor keeps its other handle's length as drawn; the brackets keep their + /// fractions of the path. False, changing nothing, for other type, when the anchor doesn't + /// exist, a degenerate `xf` or a path that would not be finite. + pub fn set_path_handle(&mut self, (si, ai): (usize, usize), out: bool, pos: Point, independent: bool) -> bool { + let xf = self.xf; + matches!(self.kind, TextKind::OnPath { .. }) + && self.reshape_local(|path, to_text| { + let Some(a) = path.anchor_mut(si, ai) else { return false }; + let mut drawn = a.transform(xf); + drawn.set_handle(out, pos, independent); + *a = drawn.transform(to_text); + true + }) + } /// Edit a copy of the area frame with `f` (given the document → text space map) and keep it /// when `f` succeeds and the result is finite. fn reshape_area(&mut self, f: impl FnOnce(&mut PathData, Affine) -> bool) -> bool { diff --git a/crates/effects/src/stroke/arrow.rs b/crates/effects/src/stroke/arrow.rs index 1a5c900954..c96dcb477c 100644 --- a/crates/effects/src/stroke/arrow.rs +++ b/crates/effects/src/stroke/arrow.rs @@ -1,5 +1,5 @@ //! Arrowheads. A head of weight `hw` (stroke weight × scale) fits a box `4·hw` long and `4·hw` -//! wide. Hollow kinds are rings (`hw/2` walls) or, for the open arrow, a chevron with `hw` arms. +//! wide; the line arrow's arms reach twice as far out ([`Arrowhead::half_width`]). Hollow kinds are rings (`hw/2` walls) or, for the open arrow, a chevron with `hw` arms. //! The stroke ends under the head at the head's *inset* from the tip: halfway into solid heads, //! in the back wall of hollow ones (with the cap kept out of the hole) and at the chevron's inner //! corner. With [`ArrowAlign::Tip`] the tip sits on the end point and the stroke is shortened by @@ -8,7 +8,7 @@ use std::borrow::Cow; -use std::f64::consts::{FRAC_PI_2, PI}; +use std::f64::consts::{FRAC_1_SQRT_2, FRAC_PI_2, PI}; use kurbo::{Affine, BezPath, ParamCurve, ParamCurveArclen, PathSeg, Point, Shape, Vec2}; use vectorcraft_doc::{ArrowAlign, Arrowhead, StrokeLayer}; @@ -252,6 +252,7 @@ const HEX: f64 = 2.0 * 1.732_050_807_568_877_2; /// Flattening tolerance of the curved local heads, in units. const LOCAL_TOL: f64 = 1e-3; +/// Where the stroke ends under a head drawn in local units ([`local`]), in those units. fn local_stop(kind: Arrowhead) -> Stop { match kind { Arrowhead::Target | Arrowhead::TagOpen | Arrowhead::DiamondOpen => Stop::Wall(4.0), @@ -261,7 +262,7 @@ fn local_stop(kind: Arrowhead) -> Stop { Arrowhead::Fork => Stop::At(2.7), Arrowhead::HalfArrowLeft | Arrowhead::HalfArrowRight | Arrowhead::Feather => Stop::At(1.3), Arrowhead::Swallowtail => Stop::At(1.4), - Arrowhead::Chevron => Stop::At(1.0), + Arrowhead::Chevron | Arrowhead::LineArrow => Stop::At(1.0), Arrowhead::Slash => Stop::At(1.2), Arrowhead::DoubleSlash => Stop::At(1.05), Arrowhead::DoubleArrow => Stop::At(1.7), @@ -273,8 +274,9 @@ fn local_stop(kind: Arrowhead) -> Stop { } /// The outline of a head added after the first ten, in local units: x from the tip (0) back -/// along the line (to at most 4), y across it (−2 to 2, positive to the right of the direction -/// the head points). Every shape is generated here. +/// along the line (to at most 4; the line arrow's square-cut arms 4.71), y across it (−2 to 2, +/// the line arrow −4 to 4; positive to the right of the direction the head points). Every shape +/// is generated here. fn local(kind: Arrowhead) -> BezPath { let mut p = BezPath::new(); let poly = |p: &mut BezPath, pts: &[(f64, f64)]| polygon(p, &pts.iter().map(|&q| Point::from(q)).collect::>()); @@ -363,6 +365,14 @@ fn local(kind: Arrowhead) -> BezPath { poly(&mut p, &[(0.0, 2.0), (0.6, 2.0), (0.6, 0.25), (4.0, 1.8), (4.0, -1.8), (0.6, -0.25), (0.6, -2.0), (0.0, -2.0)]) } Arrowhead::Oval => p.extend(kurbo::Ellipse::new((2.0, 0.0), (2.0, 1.2), 0.0).path_elements(LOCAL_TOL)), + Arrowhead::LineArrow => { + // Arms one unit thick (the head's weight: the line's at 100 % for lines of 0.25 pt or + // more) at right angles to each other, from a sharp tip to their outer corners at + // (4, ±4), cut square across: a unit across an arm at 45° is ½√2 along each axis, and + // the arms' inner edges meet √2 behind the tip. + let t = FRAC_1_SQRT_2; + poly(&mut p, &[(0.0, 0.0), (4.0, 4.0), (4.0 + t, 4.0 - t), (2.0 * t, 0.0), (4.0 + t, t - 4.0), (4.0, -4.0)]); + } // The first ten are drawn by `shape`. Arrowhead::Triangle | Arrowhead::TriangleOpen diff --git a/crates/effects/src/stroke/tests_arrows.rs b/crates/effects/src/stroke/tests_arrows.rs index 39d6d9d57d..4328048991 100644 --- a/crates/effects/src/stroke/tests_arrows.rs +++ b/crates/effects/src/stroke/tests_arrows.rs @@ -1,6 +1,6 @@ -//! Every arrowhead's outline: drawn, inside its box (4 × 4 weights; the open arrow's square-cut -//! arms reach a little further back), without self-intersections, and covering the end of the -//! stroke under it. +//! Every arrowhead's outline: drawn, inside its reach and half width (4 × 4 weights for most; the +//! open arrow's square-cut arms reach a little further back, the line arrow's twice as far out), +//! without self-intersections, and covering the end of the stroke under it. use kurbo::{BezPath, PathEl, Point, Shape}; use vectorcraft_color::{Color, Paint}; @@ -53,7 +53,13 @@ fn every_outline_is_drawn_inside_its_box_without_self_intersections() { let h = head(kind); assert!(h.outline.area().abs() > 4.0, "{kind:?} is drawn"); let b = h.outline.bounding_box(); - assert!(b.x0 >= 91.0 - 1e-6 && b.x1 <= 100.0 + 1e-6 && b.y0 >= -4.0 - 1e-6 && b.y1 <= 4.0 + 1e-6, "{kind:?} leaves its box: {b:?}"); + let (reach, side) = (2.0 * kind.reach(), 2.0 * kind.half_width()); + assert!(b.x1 <= 100.0 + 1e-6 && b.y0 >= -side - 1e-6 && b.y1 <= side + 1e-6, "{kind:?} leaves its box: {b:?}"); + if kind.half_width() == 2.0 { + assert!(b.x0 >= 91.0 - 1e-6, "{kind:?} is longer than the 4 × 4 box: {b:?}"); + } + let far = contours(&h.outline).iter().flatten().map(|p| p.distance(h.tip)).fold(0.0, f64::max); + assert!(far <= reach + 1e-6, "{kind:?} reaches {far} from its tip, past {reach}"); let edges: Vec<(Point, Point)> = contours(&h.outline).iter().flat_map(|c| (0..c.len()).map(|i| (c[i], c[(i + 1) % c.len()]))).collect(); assert!(edges.len() >= 3, "{kind:?}"); for (i, a) in edges.iter().enumerate() { @@ -74,6 +80,31 @@ fn the_stroke_ends_inside_every_head() { } } +#[test] +fn the_line_arrow_is_a_right_angle_of_two_arms_as_thick_as_the_line() { + // Weight 2 at 100 %: a local unit (x back from the tip, y across) is 2 pt. + let h = head(Arrowhead::LineArrow); + let at = |x: f64, y: f64| Point::new(100.0 - 2.0 * x, 2.0 * y); + // A sharp tip on the end point; outer corners 4 units back and out, square-cut ends. + let pts: Vec = contours(&h.outline).concat(); + for (corner, name) in [(at(0.0, 0.0), "tip"), (at(4.0, 4.0), "right corner"), (at(4.0, -4.0), "left corner")] { + assert!(pts.iter().any(|p| p.distance(corner) < 1e-9), "{name} {corner:?} in {pts:?}"); + } + // Open between the arms, solid at the tip. + assert_eq!(h.outline.winding(at(2.5, 0.0)), 0); + assert_ne!(h.outline.winding(at(0.7, 0.0)), 0); + // Halfway along each arm, 45° off the line, it is one unit (the line's weight) across. + let s = std::f64::consts::FRAC_1_SQRT_2; + for side in [1.0, -1.0] { + let (mx, my) = (2.0 + 0.5 * s, side * (2.0 - 0.5 * s)); + let (nx, ny) = (-side * s, s); + for (d, inside) in [(0.45, true), (-0.45, true), (0.55, false), (-0.55, false)] { + let w = h.outline.winding(at(mx + nx * d, my + ny * d)); + assert_eq!(w != 0, inside, "arm {side} at {d} across"); + } + } +} + #[test] fn half_arrows_barb_on_their_own_side() { // Pointing along +x on a y-down page, left is −y. diff --git a/crates/engine/Cargo.toml b/crates/engine/Cargo.toml index ef403dc80b..836d4b7448 100644 --- a/crates/engine/Cargo.toml +++ b/crates/engine/Cargo.toml @@ -40,6 +40,7 @@ vectorcraft-metafile = { workspace = true } vectorcraft-plugins = { workspace = true } vectorcraft-affinity = { workspace = true } vectorcraft-scriptcheck = { workspace = true } +vectorcraft-js = { workspace = true } # The commands' parameter schemas (schemas.rs). vectorcraft-apischema = { workspace = true } image = { workspace = true } diff --git a/crates/engine/src/cmd/distortcmds/perspective.rs b/crates/engine/src/cmd/distortcmds/perspective.rs index a561e50998..8c35254494 100644 --- a/crates/engine/src/cmd/distortcmds/perspective.rs +++ b/crates/engine/src/cmd/distortcmds/perspective.rs @@ -635,6 +635,7 @@ pub(crate) fn finish_edit_text(st: &mut crate::DocState, id: NodeId) { } }; st.change_unsaved(clear); + st.history.rewrites += 1; for e in st.history.undo.iter_mut().chain(st.history.redo.iter_mut()) { let saved = Arc::ptr_eq(&e.doc, &st.saved_doc); clear(&mut e.doc); diff --git a/crates/engine/src/cmd/fileio/tests.rs b/crates/engine/src/cmd/fileio/tests.rs index c523284ba8..6236d281e2 100644 --- a/crates/engine/src/cmd/fileio/tests.rs +++ b/crates/engine/src/cmd/fileio/tests.rs @@ -914,3 +914,34 @@ fn read_path_for_a_named_importer_stops_at_the_limit() { assert!(e.to_string().contains("larger than") && e.to_string().contains("drawing.tuv"), "{e}"); let _ = std::fs::remove_dir_all(&dir); } + +/// #3084, #2096: Export for Screens writes JPGs a strict reader opens, in every colour model and at +/// the qualities and scales the reports used. A four-component (CMYK) file has no JFIF segment, +/// which describes only one- and three-component images (#3140); RGB and gray files keep it. +#[test] +fn export_for_screens_jpgs_open_in_every_colour_model() { + let mut s = session(100.0, 80.0, 1); + s.execute("paint.setFill", &json!({"color": "#cc3300"})).unwrap(); + s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 60, "height": 40})).unwrap(); + for (model, components) in [("rgb", 3), ("cmyk", 4), ("gray", 1)] { + for quality in [100, 80, 50] { + let r = s + .execute( + "document.exportForScreens", + &json!({"formats": [{"format": "jpg"}, {"format": "jpg", "scale": 2}], "settings": {"jpg": {"colorModel": model, "quality": quality}}}), + ) + .unwrap(); + let files = r["files"].as_array().unwrap(); + assert_eq!(files.len(), 2, "{model} {quality}: {r}"); + for (f, width) in files.iter().zip([100, 200]) { + let bytes = b64(f); + let what = format!("{model} q{quality} {}", f["name"]); + assert_eq!(bytes.get(..2), Some(&[0xFF, 0xD8][..]), "{what}: starts with SOI"); + let jfif = bytes.get(2..4) == Some(&[0xFF, 0xE0][..]); + assert_eq!(jfif, components != 4, "{what}: JFIF only on one- and three-component files"); + let image = image::load_from_memory(&bytes).unwrap_or_else(|e| panic!("{what}: {e}")); + assert_eq!(image.width(), width, "{what}"); + } + } + } +} diff --git a/crates/engine/src/cmd/prefscmds.rs b/crates/engine/src/cmd/prefscmds.rs index a0557d2134..aec3e86f94 100644 --- a/crates/engine/src/cmd/prefscmds.rs +++ b/crates/engine/src/cmd/prefscmds.rs @@ -140,6 +140,7 @@ pub const PREF_SPECS: &[PrefSpec] = &[ p!("disableAutoAddDelete", "General", "Options", "Disable Auto Add/Delete", bool), p!("usePreciseCursors", "General", "Options", "Use Precise Cursors", bool), p!("showToolTips", "General", "Options", "Show Tool Tips", bool), + p!("showExternalScriptWarning", "General", "Options", "Show External Script Warning", 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/recovery.rs b/crates/engine/src/cmd/recovery.rs index a06597ac8a..4cf070c6ae 100644 --- a/crates/engine/src/cmd/recovery.rs +++ b/crates/engine/src/cmd/recovery.rs @@ -766,11 +766,14 @@ pub fn skip_reason(s: &Session, st: &DocState) -> Option<&'static str> { return Some("unchanged since its last recovery copy"); } if s.prefs.recovery_off_for_complex && object_count(&st.doc) > COMPLEX_OBJECTS { - return Some("complex document (Data Recovery is off for complex documents)"); + return Some(COMPLEX_SKIP); } None } +/// Why a complex document with unsaved changes gets no copy. +const COMPLEX_SKIP: &str = "complex document (Data Recovery is off for complex documents)"; + /// A file name part from a title: letters, digits, `-`, `_` and spaces (others as `-`). fn safe_stem(title: &str) -> String { let stem: String = fileio::file_stem(title).chars().map(|c| if c.is_alphanumeric() || matches!(c, '-' | '_' | ' ') { c } else { '-' }).collect(); @@ -866,8 +869,35 @@ fn remove_copy(s: &Session, file: &str) { } } -/// Document `uid` was saved, reverted or closed: its recovery copy goes. +/// Closed document `st`'s recovery copy goes. +pub(crate) fn forget_closed(s: &Session, st: &crate::DocState) { + if let Some(copy) = &st.recovery { + remove_copy(s, ©.file); + } +} + +/// Writes a copy of every document that needs one now. An error when a document with unsaved +/// changes would be left without a current copy. +pub(crate) fn save_copies(s: &mut Session) -> Result<()> { + let store = need_store(s, "script.run")?; + let (jobs, _) = jobs(s, &store)?; + let uncopied = s.documents().iter().any(|st| skip_reason(s, st) == Some(COMPLEX_SKIP)); + if uncopied { + return Err(EngineError::Other("a document with unsaved changes has no recovery copy".into())); + } + for j in jobs { + j.write(store.as_ref()).map_err(EngineError::Other)?; + j.finish(s); + } + Ok(()) +} + +/// Document `uid` was saved, reverted or closed: its recovery copy goes. While a script runs the +/// run's commit settles that. pub fn forget(s: &mut Session, uid: u64) { + if s.script_in_run { + return; + } let Some(copy) = s.document_mut(uid).and_then(|st| st.recovery.take()) else { return }; remove_copy(s, ©.file); } diff --git a/crates/engine/src/cmd/scripts.rs b/crates/engine/src/cmd/scripts.rs index 45f2670488..b8b5448817 100644 --- a/crates/engine/src/cmd/scripts.rs +++ b/crates/engine/src/cmd/scripts.rs @@ -11,21 +11,139 @@ use vectorcraft_scriptcheck::{Limits, Loaded, Loader, Report}; /// The ids a reply can hold, for the windows that show it. pub use vectorcraft_scriptcheck::{IncludeStatus, Need, OUTSIDE, PROBLEMS}; -use super::{CommandSpec, Result, Session, always, bad, bool_or, cmd, str_param}; +use super::{CommandSpec, EngineError, Result, Session, always, bad, bool_or, cmd, str_param}; +use crate::script; /// The extensions of the scripts File › Open shows a check for. pub const EXTS: &[&str] = &["jsx", "jsxinc", "jsxbin"]; +/// The extensions of the scripts `script.run` takes as a file, in any case. +pub const RUN_EXTS: &[&str] = &["js", "jsx"]; + +/// Does `path` name a file `script.run` takes? +pub fn runs(path: &str) -> bool { + std::path::Path::new(path).extension().and_then(|e| e.to_str()).is_some_and(|e| RUN_EXTS.iter().any(|x| e.eq_ignore_ascii_case(x))) +} + pub fn specs() -> Vec { - vec![cmd!( - query "script.check", - "Check Script", - [], - None, - "{path? | data?: the script's text | dataBase64?, name?: the file's name (default: the path's; with a path, only the reply's name), includes?: false (with a path: also check the files its #include lines name, inside the script's folder; not on the web)} check a script written for the reference app (.jsx, .jsxinc, .js, or a compiled .jsxbin) without running any of it → {name, kind: script|compiled|module|notText|tooLarge, needs: [language|dom|files|menuCommands|dialogs|hostOnly], lines, targets: [{value, app, instance?, version?, locale?, line, file?}], directives: [{name, value, line, form: \"#\"|\"//@\", file?}], includes: [{value, line, status: checked|missing|notFollowed|cycle|notRead|limit|unreadable, path?, file?}], features: [{id, count, lines}], dom: {members: [{path, count}], types: [{name, count}]}, menuCommands: {strings: [{value, count, lines}], dynamic}, outside: [{id: filesWritten|filesOpened|network|nativeCode|otherApps|environment|unseenCode|preferences, count, lines, modes?}], problems: [{code, line?, file?, detail?}], truncated} (file: the included file it is in; lines: at most 20 of the script's own, while counts include the included files; at most 8 MiB a file and 32 MiB in all, 64 included files 16 deep, 1,024 paths looked up for them, 1,000 entries a list, text echoed cut to 120 characters)", - always, - check - )] + vec![ + cmd!( + query "script.run", + "Run Script", + [], + None, + "{path?: a .js or .jsx file | source?: the script's text (exactly one of the two), name?: the name errors and the report use (default: the path's file name, or \"script\"), args?: {…} (at most 1 MiB as JSON; vc.args in the script), answers?: {} (no prompts exist yet: only an empty object is taken), maxFuel?: whole number from 1 to 100000000000 (instructions in all; default 1000000000)} run a JavaScript file against the open documents, through the vc object: vc.run(id, params) runs a command and returns its result, a failed command throws an error the script can catch and puts back the documents and the session state it changed, while any file it wrote stays written and is named; vc.document is a snapshot of the active document or null; vc.commands lists the commands a script may run; vc.log(value) adds to the report; vc.args is args; vc.api.version and vc.api.has(feature) describe the API. The run is one transaction: on success each changed document gets one undo step, Run Script, and each preference it changed keeps its value, and on an uncaught error, a limit or script.stop every open document and the session go back as they were; files a command wrote before that stay written and are named. While it runs, other commands that change anything end with a busy error. Commands that change anything outside the documents (script.*, except script.check, plugin.*, prefs.*, actionSet.*, shortcutSet.*, help.*, print.*, library.*, importMatches.*, edit.undoGroup.*, file.recovery.*, stroke.widthProfile.*, saving, importing or deleting a preset, text.addFontFiles, text.findFontFiles, text.rescanFonts, links.findFiles, file.place.queue, color.loadProfile, color.removeProfile, file.print, view.proofSetup, view.proofColors, view.overprintPreview, view.separationsPreview) throw. VectorCraft's own limits: 8 MiB of source, 256 MiB of heap (128 MiB on the web), 2000000 host calls, 200000000 instructions without a pause, 64 levels, 16 MiB and 1048576 entries for a value crossing to or from a command, 10000 log entries and 4 MiB of log, and 100000 objects and 512 MiB of new document data, past which a person is asked to continue or stop and a run with nobody to ask ends → {ok: true, name, changed: [document names], written: [paths], log: [values], fuelUsed, hostCalls}, or, in the app, {running: true, name} and the report later in ui.inspect's scriptReport", + always, + run + ), + cmd!( + query "script.stop", + "Stop Script", + [], + None, + "{} stop the running script, which puts every document back as it was before the run; asking again while it stops is harmless → {stopped: whether a script was running}", + always, + stop + ), + cmd!( + query "script.check", + "Check Script", + [], + None, + "{path? | data?: the script's text | dataBase64?, name?: the file's name (default: the path's; with a path, only the reply's name), includes?: false (with a path: also check the files its #include lines name, inside the script's folder; not on the web)} check a script written for the reference app (.jsx, .jsxinc, .js, or a compiled .jsxbin) without running any of it → {name, kind: script|compiled|module|notText|tooLarge, needs: [language|dom|files|menuCommands|dialogs|hostOnly], lines, targets: [{value, app, instance?, version?, locale?, line, file?}], directives: [{name, value, line, form: \"#\"|\"//@\", file?}], includes: [{value, line, status: checked|missing|notFollowed|cycle|notRead|limit|unreadable, path?, file?}], features: [{id, count, lines}], dom: {members: [{path, count}], types: [{name, count}]}, menuCommands: {strings: [{value, count, lines}], dynamic}, outside: [{id: filesWritten|filesOpened|network|nativeCode|otherApps|environment|unseenCode|preferences, count, lines, modes?}], problems: [{code, line?, file?, detail?}], truncated} (file: the included file it is in; lines: at most 20 of the script's own, while counts include the included files; at most 8 MiB a file and 32 MiB in all, 64 included files 16 deep, 1,024 paths looked up for them, 1,000 entries a list, text echoed cut to 120 characters)", + always, + check + ), + ] +} + +/// A refusal of `script.run`'s parameters, which only a program's own call can give. +fn param(msg: impl Into) -> EngineError { + EngineError::BadParams { cmd: "script.run".into(), msg: msg.into() } +} + +/// `maxFuel`: a whole number from 1 to [`script::MAX_FUEL`], or the default when omitted. +fn max_fuel(p: &Value) -> Result { + let Some(v) = p.get("maxFuel") else { return Ok(script::DEFAULT_FUEL) }; + v.as_u64() + .filter(|n| (1..=script::MAX_FUEL).contains(n)) + .ok_or_else(|| param(format!("`maxFuel` must be a whole number from 1 to {}", script::MAX_FUEL))) +} + +/// The text of a script read as bytes: a byte order mark is left out, and compiled scripts and +/// bytes that are not UTF-8 are refused. +fn script_text(bytes: &[u8]) -> Result { + if bytes.starts_with(b"@JSXBIN@") { + return Err(EngineError::Other(COMPILED.to_string())); + } + let text = std::str::from_utf8(bytes).map_err(|_| EngineError::Other(NOT_TEXT.to_string()))?; + Ok(text.strip_prefix('\u{feff}').unwrap_or(text).to_string()) +} + +const COMPILED: &str = "this is a compiled script, which cannot be run; use its source text"; +const NOT_TEXT: &str = "the script is not UTF-8 text"; +/// The error for a script over [`script::MAX_SOURCE_BYTES`]. +pub const TOO_LARGE: &str = "the script is too large to run"; + +fn run(s: &mut 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())), + Some(_) => Err(param(format!("`{key}` must be a string"))), + }; + let (path, source, given_name) = (optional_str("path")?, optional_str("source")?, optional_str("name")?); + // Checked before anything copies or writes out `args`, which would go one call deeper per level. + if let Some(place) = p.get("args").and_then(script::too_deep) { + return Err(param(format!("`args{place}` is nested more than 64 levels deep"))); + } + let args = match p.get("args") { + None => serde_json::Map::new(), + Some(Value::Object(o)) => o.clone(), + Some(_) => return Err(param("`args` must be an object")), + }; + if serde_json::to_vec(&args).map_or(true, |b| b.len() > script::MAX_ARGS_BYTES) { + return Err(param("`args` is larger than 1 MiB")); + } + match p.get("answers") { + None => {} + Some(Value::Object(o)) if o.is_empty() => {} + Some(_) => return Err(param("`answers` must be an empty object: scripts cannot ask questions yet")), + } + let fuel = max_fuel(p)?; + let text = match (path, source) { + (Some(""), None) => return Err(param("`path` is empty")), + (Some(path), None) => { + if path.to_ascii_lowercase().ends_with(".jsxbin") { + return Err(EngineError::Other(COMPILED.to_string())); + } + if !runs(path) { + return Err(param("`path` must name a .js or .jsx file")); + } + // One byte more than a script may have shows that the file is too large. + let bytes = super::fileio::read_file_head(path, script::MAX_SOURCE_BYTES + 1)?; + if bytes.len() > script::MAX_SOURCE_BYTES { + return Err(EngineError::Other(TOO_LARGE.to_string())); + } + script_text(&bytes)? + } + (None, Some(source)) => { + if source.len() > script::MAX_SOURCE_BYTES { + return Err(EngineError::Other(TOO_LARGE.to_string())); + } + script_text(source.as_bytes())? + } + _ => return Err(param("give exactly one of `path` and `source`")), + }; + let name = given_name.map(str::to_string).or_else(|| path.map(super::fileio::file_name)).unwrap_or_else(|| "script".to_string()); + s.script_start(script::Request { name: name.clone(), source: text, args, fuel })?; + if s.script_frames { + return Ok(json!({"running": true, "name": name})); + } + s.script_run_to_end() +} + +fn stop(s: &mut Session, _: &Value) -> Result { + Ok(json!({"stopped": s.script_request_stop()})) } /// The folder a script is in, which its included files are read from. diff --git a/crates/engine/src/cmd/stroke.rs b/crates/engine/src/cmd/stroke.rs index 1fb3373c7a..e97659bfc9 100644 --- a/crates/engine/src/cmd/stroke.rs +++ b/crates/engine/src/cmd/stroke.rs @@ -20,7 +20,7 @@ pub fn specs() -> Vec { "Stroke Options", ["Window", "Stroke"], None, - "{weight?: pt, cap?: butt|round|square, join?: miter|round|bevel, miterLimit?, align?: center|inside|outside, dash?: [d,g,…]|null (a 0 dash with a round or projecting cap draws dots or squares; a new pattern keeps the current offset and alignment), dashOffset? (exact dashes only), alignDashes?: bool (true: dashes fitted to corners and path ends, every run between them holding whole periods with a dash centred on each corner and end; false, the default for a new pattern: exact lengths), startArrow?, endArrow?: Arrow|ArrowOpen|Barbed|Concave|DoubleArrow|HalfArrowLeft|HalfArrowRight|Chevron|Feather|Swallowtail|Triangle|TriangleOpen|TriangleReverse|TriangleBar|Kite|Leaf|Drop|Circle|CircleOpen|HalfCircle|Oval|Target|Square|SquareOpen|Tag|TagOpen|Diamond|DiamondOpen|Hexagon|HexagonOpen|Star|Cross|Plus|Bar|DoubleBar|DotOnBar|Slash|DoubleSlash|Bracket|Fork|null (HalfArrowLeft/Right: one barb, left or right of the direction the head points), arrowAlign?: \"extend\" (tip past the end point, default)|\"tip\" (tip on the end point; the stroke is shortened), profile?: \"uniform\"|\"lens\"|\"taperStart\"|\"taperEnd\"|\"pinch\"|\"teardrop\"|\"wave\"|a saved profile's name (stroke.widthProfile.list), widthPoints?, gradientMode? (as document.inspect reports them in strokeOptions, so those read back unchanged; ignored here: a custom profile is set with the Width tool, gradientMode with paint.editGradient), item?: stroke item index|null (omitted: the Appearance panel's active item if it is a stroke, else the top stroke, created when missing), ids?|id?, target?: \"object\"|\"contents\", aligned?: bool (index and item are rows of the first target's stack: each other target edits its equal one, as the Appearance panel does for a mixed selection)} Without a stroke item, type takes weight, cap, join, miterLimit, align (around its glyph outlines; the type stays live) and the dash options as its characters' stroke (every run; text.setRangeStyle `strokeOptions` styles a range), and images and symbol instances (also in groups) are left alone. With nothing selected (and no ids) they set up the next object drawn (appearance.newArt; weight always does) → {objects: how many objects took the stroke options}", + "{weight?: pt, cap?: butt|round|square, join?: miter|round|bevel, miterLimit?, align?: center|inside|outside, dash?: [d,g,…]|null (a 0 dash with a round or projecting cap draws dots or squares; a new pattern keeps the current offset and alignment), dashOffset? (exact dashes only), alignDashes?: bool (true: dashes fitted to corners and path ends, every run between them holding whole periods with a dash centred on each corner and end; false, the default for a new pattern: exact lengths), startArrow?, endArrow?: Arrow|ArrowOpen|LineArrow|Barbed|Concave|DoubleArrow|HalfArrowLeft|HalfArrowRight|Chevron|Feather|Swallowtail|Triangle|TriangleOpen|TriangleReverse|TriangleBar|Kite|Leaf|Drop|Circle|CircleOpen|HalfCircle|Oval|Target|Square|SquareOpen|Tag|TagOpen|Diamond|DiamondOpen|Hexagon|HexagonOpen|Star|Cross|Plus|Bar|DoubleBar|DotOnBar|Slash|DoubleSlash|Bracket|Fork|null (HalfArrowLeft/Right: one barb, left or right of the direction the head points), arrowAlign?: \"extend\" (tip past the end point, default)|\"tip\" (tip on the end point; the stroke is shortened), profile?: \"uniform\"|\"lens\"|\"taperStart\"|\"taperEnd\"|\"pinch\"|\"teardrop\"|\"wave\"|a saved profile's name (stroke.widthProfile.list), widthPoints?, gradientMode? (as document.inspect reports them in strokeOptions, so those read back unchanged; ignored here: a custom profile is set with the Width tool, gradientMode with paint.editGradient), item?: stroke item index|null (omitted: the Appearance panel's active item if it is a stroke, else the top stroke, created when missing), ids?|id?, target?: \"object\"|\"contents\", aligned?: bool (index and item are rows of the first target's stack: each other target edits its equal one, as the Appearance panel does for a mixed selection)} Without a stroke item, type takes weight, cap, join, miterLimit, align (around its glyph outlines; the type stays live) and the dash options as its characters' stroke (every run; text.setRangeStyle `strokeOptions` styles a range), and images and symbol instances (also in groups) are left alone. With nothing selected (and no ids) they set up the next object drawn (appearance.newArt; weight always does) → {objects: how many objects took the stroke options}", has_doc, stroke_set ), diff --git a/crates/engine/src/cmd/symboledit.rs b/crates/engine/src/cmd/symboledit.rs index a3745975b0..22cfc74e9f 100644 --- a/crates/engine/src/cmd/symboledit.rs +++ b/crates/engine/src/cmd/symboledit.rs @@ -140,7 +140,7 @@ pub(crate) fn enter(s: &mut Session, p: &Value) -> Result { } s.end_text_edit(); let st = s.doc()?; - let back = Return { redo: st.history.redo.clone(), before: Some(st.doc.clone()) }; + let back = Return { redo: Arc::new(st.history.redo.clone()), before: Some(st.doc.clone()) }; let (isolation, active_layer) = (st.isolation, st.active_layer); let layer = s.edit(ENTER, |d, sel| { let layer = begin(d, sel, &name, xf, instance)?; @@ -229,7 +229,7 @@ pub(crate) fn leave(s: &mut Session, _: &Value) -> Result { } st.selection = Arc::unwrap_or_clone(entry.selection); st.selection.prune(&st.doc); - st.history.redo = redo; + st.history.redo = Arc::unwrap_or_clone(redo); st.revision += 1; } else { s.edit("Exit Symbol Editing Mode", |d, sel| { @@ -257,9 +257,10 @@ pub(crate) fn finish(d: &mut Document, sel: &mut Selection) { /// The redo steps entering symbol editing mode cleared, which leaving without an edit gives back, /// and the document entering started from, which tells the entering step apart from any other. +/// Copies of the document's state share the redo steps. #[derive(Clone, Debug, Default)] pub(crate) struct Return { - redo: Vec, + redo: Arc>, before: Option>, } diff --git a/crates/engine/src/cmd/symbollib.rs b/crates/engine/src/cmd/symbollib.rs index 1e74eb4563..fe3f1149da 100644 --- a/crates/engine/src/cmd/symbollib.rs +++ b/crates/engine/src/cmd/symbollib.rs @@ -157,6 +157,7 @@ pub struct BuiltinSymbolLibrary { pub const BUILTIN: &[BuiltinSymbolLibrary] = &[ BuiltinSymbolLibrary { id: "basic-shapes", name: "Basic Shapes", make: basic_shapes }, BuiltinSymbolLibrary { id: "ui-frames", name: "UI Frames", make: ui_frames }, + BuiltinSymbolLibrary { id: "map-markers", name: "Map Markers", make: map_markers }, ]; /// Built-in library `id`, made once. @@ -221,6 +222,33 @@ fn ui_frames() -> SymbolLibrary { SymbolLibrary { name: "UI Frames".into(), doc } } +/// Map Markers: pin, flag, crosshair and checkpoint for map/HUD art (original, no 9-slice). +fn map_markers() -> SymbolLibrary { + let c = Point::ZERO; + let pin = [(0.0, 22.0), (-9.0, 4.0), (-12.0, -6.0), (-8.0, -16.0), (0.0, -20.0), (8.0, -16.0), (12.0, -6.0), (9.0, 4.0)]; + let flag = [(-16.0, 22.0), (-12.0, 22.0), (-12.0, -8.0), (18.0, -14.0), (-12.0, -20.0), (-12.0, -22.0), (-16.0, -22.0)]; + let pin: Vec = pin.iter().map(|&(x, y)| Point::new(x, y)).collect(); + let flag: Vec = flag.iter().map(|&(x, y)| Point::new(x, y)).collect(); + let markers = [ + ("Pin", vectorcraft_geom::PathData::single(vectorcraft_geom::SubPath::polyline(&pin, true)), "#e74c3c"), + ("Flag", vectorcraft_geom::PathData::single(vectorcraft_geom::SubPath::polyline(&flag, true)), "#3498db"), + ("Crosshair", shapes::star(c, 20.0, 5.0, 4, 0.0), "#2c3e50"), + ("Checkpoint", shapes::polygon(c, 18.0, 4, 0.0), "#27ae60"), + ]; + let mut doc = Document::new(100.0, 100.0); + for (name, path, hex) in markers { + let fill = Color::from_hex(hex).unwrap_or(Color::BLACK); + let edge = fill.lerp(&Color::BLACK, 0.35); + let id = doc.alloc_id(); + let art = Node::path(id, path, Appearance::basic(Paint::solid(fill), Paint::solid(edge), 1.25)); + let Ok((art, size, _)) = normalize(art) else { continue }; + doc.symbols.push(Symbol { dynamic: false, name: name.into(), art: Arc::new(art) }); + set_natural_size(&mut doc, name, Some(size)); + } + doc.title = "Map Markers".into(); + SymbolLibrary { name: "Map Markers".into(), doc } +} + /// An instance of symbol `name` (what the resource gathering follows). fn instance(name: &str) -> Node { Node::new(NodeId(0), NodeKind::SymbolInstance { symbol: name.into(), xf: Affine::IDENTITY }) diff --git a/crates/engine/src/cmd/typecmd.rs b/crates/engine/src/cmd/typecmd.rs index a4fe337626..2257b1a8ae 100644 --- a/crates/engine/src/cmd/typecmd.rs +++ b/crates/engine/src/cmd/typecmd.rs @@ -115,6 +115,15 @@ pub fn specs() -> Vec { has_doc, reshape_path ), + cmd!( + "text.setPathHandle", + "Move Type Path Handle", + [], + None, + "{id, subpath?, anchor, which: \"in\"|\"out\", x, y, independent?: bool} move a direction handle of an anchor of type on a path's path to (x, y), as path.setHandle moves a path's (independent: that side only, the anchor becomes a corner); the start and end brackets keep their fractions of the path and the text reflows along it (what Direct Selection does dragging a handle of the path)", + has_doc, + set_path_handle + ), cmd!( "text.fitHeadline", "Fit Headline", @@ -1268,6 +1277,35 @@ fn reshape_path(s: &mut Session, p: &Value) -> Result { ok() } +fn set_path_handle(s: &mut Session, p: &Value) -> Result { + const C: &str = "text.setPathHandle"; + let id = id_param(p, "id").ok_or_else(|| bad(C, "missing id"))?; + let si = super::draw2::usize_opt(p, "subpath", C)?.unwrap_or(0); + let ai = p.get("anchor").and_then(Value::as_u64).map(index).ok_or_else(|| bad(C, "missing anchor"))?; + let out = str_param(p, "which") != Some("in"); + let pos = vectorcraft_geom::Point::new(f64_req(p, "x", C)?, f64_req(p, "y", C)?); + let independent = switch_or(p, "independent", false, C)?; + let node = s.doc()?.doc.node(id); + let on_path = matches!(node.map(|n| &n.kind), Some(NodeKind::Text(t)) if matches!(t.kind, vectorcraft_doc::TextKind::OnPath { .. })); + if !on_path || node.is_some_and(|n| n.extras().perspective.is_some()) { + return Err(bad(C, "not type on a path outside perspective")); + } + s.edit("Reshape Type Path", |doc, _| { + let Some(NodeKind::Text(t)) = doc.node_mut(id).map(|n| &mut n.kind) else { return Err(EngineError::NoNode(id)) }; + let before = t.kind.clone(); + let within = |t: &TextObject| { + t.type_path().and_then(|p| p.bounds()).is_some_and(|b| [b.x0, b.y0, b.x1, b.y1].iter().all(|v| v.abs() <= crate::MAX_COORD)) + }; + if !(t.set_path_handle((si, ai), out, pos, independent) && within(t)) { + t.kind = before; + return Err(bad(C, "no such path anchor, or the path would reach past the canvas")); + } + refresh_bounds(t); + Ok(()) + })?; + ok() +} + #[cfg(test)] mod area_tests; diff --git a/crates/engine/src/cmd/typecmd/area_tests.rs b/crates/engine/src/cmd/typecmd/area_tests.rs index 88ccb36da5..571c9c3469 100644 --- a/crates/engine/src/cmd/typecmd/area_tests.rs +++ b/crates/engine/src/cmd/typecmd/area_tests.rs @@ -2081,3 +2081,35 @@ fn fit_min_percent_for_several_frames_keeps_each_frames_fit() { assert_eq!(fit(&s, plain), vectorcraft_doc::AreaFit::None, "the plain frame doesn't start shrinking"); assert_eq!(fit(&s, shrink), vectorcraft_doc::AreaFit::ShrinkText { min_percent: 30.0 }); } + +/// #3565: `text.setPathHandle` moves a direction handle of type on a path's path, in document +/// space, as `path.setHandle` moves a path's: a smooth anchor's other handle turns with it at +/// its length, `independent` leaves it and makes the anchor a corner; one undo step. +#[test] +fn set_path_handle_reshapes_type_on_a_path() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 600, "height": 400})).unwrap(); + let path = + s.execute("path.create", &json!({"anchors": [{"x": 100, "y": 300, "in": [50, 300], "out": [150, 300]}, {"x": 400, "y": 300}]})).unwrap(); + let text = s.execute("text.createInPath", &json!({"path": path["id"], "mode": "onPath", "text": "Along the curve"})).unwrap(); + let id = NodeId(text["id"].as_u64().unwrap()); + let first = |s: &Session| match &s.doc().unwrap().doc.node(id).unwrap().kind { + NodeKind::Text(t) => *t.type_path().unwrap().subpaths[0].anchors.first().unwrap(), + _ => panic!("not text"), + }; + let smooth = first(&s).kind == vectorcraft_geom::AnchorKind::Smooth; + s.execute("text.setPathHandle", &json!({"id": id.0, "anchor": 0, "which": "out", "x": 100, "y": 250})).unwrap(); + let a = first(&s); + assert!((a.h_out.x - 100.0).abs() < 1e-6 && (a.h_out.y - 250.0).abs() < 1e-6, "{a:?}"); + if smooth { + assert!((a.h_in.x - 100.0).abs() < 1e-6 && (a.h_in.y - 350.0).abs() < 1e-6, "smooth: the in handle turns with it at its length: {a:?}"); + } + s.execute("text.setPathHandle", &json!({"id": id.0, "anchor": 0, "which": "in", "x": 60, "y": 300, "independent": true})).unwrap(); + let b = first(&s); + assert_eq!(b.h_out, a.h_out, "independent: the other handle stays"); + assert_eq!(b.kind, vectorcraft_geom::AnchorKind::Corner); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(first(&s), a, "one undo step each"); + assert!(s.execute("text.setPathHandle", &json!({"id": id.0, "anchor": 9, "which": "out", "x": 0, "y": 0})).is_err(), "no such anchor"); + assert!(s.execute("text.setPathHandle", &json!({"id": path["id"], "anchor": 0, "which": "out", "x": 0, "y": 0})).is_err(), "not type"); +} diff --git a/crates/engine/src/command_sets.rs b/crates/engine/src/command_sets.rs index 38ce14cab7..77068d125f 100644 --- a/crates/engine/src/command_sets.rs +++ b/crates/engine/src/command_sets.rs @@ -83,6 +83,7 @@ pub(crate) fn strip_replay_only(id: &str, p: &mut Value) { /// Instances and Lock Guides change the selection, and the proof views, the preferences and added /// fonts give the documents new revisions (they draw again, and type lays out again). const WAIT_FOR_TOOL_EDIT: &[&str] = &[ + "script.run", "command.batch", "document.find", "symbol.selectInstances", diff --git a/crates/engine/src/doc_state.rs b/crates/engine/src/doc_state.rs index 736b873d06..d0e4862404 100644 --- a/crates/engine/src/doc_state.rs +++ b/crates/engine/src/doc_state.rs @@ -446,7 +446,7 @@ impl DocState { } let e = HistoryEntry::kept(label, doc, selection, &self.doc); self.history.undo.push(e); - self.history.redo.clear(); + self.history.clear_redo(); self.history.trim(); } /// End the interaction in progress, undoing what it changed. diff --git a/crates/engine/src/error.rs b/crates/engine/src/error.rs index 8d939db77b..d32fda613d 100644 --- a/crates/engine/src/error.rs +++ b/crates/engine/src/error.rs @@ -1,5 +1,8 @@ use super::{NodeId, cancel}; +/// The text of [`EngineError::Busy`], which ends every error a frontend reports for it. +pub const SCRIPT_BUSY: &str = "a script is running: stop it or wait for it to finish"; + #[derive(Debug, thiserror::Error)] pub enum EngineError { #[error("unknown command `{0}`")] @@ -20,6 +23,9 @@ pub enum EngineError { /// The caller asked for the command to stop ([`cancel`]). It changed nothing. #[error("cancelled; nothing was changed")] Cancelled, + /// A running script holds the documents until it ends. Nothing was changed. + #[error("{}", SCRIPT_BUSY)] + Busy, /// A bug: the command panicked. The document was rolled back to its state before the command. #[error("internal error in `{cmd}`: {msg} (the document was left as it was before; please report this bug)")] Internal { cmd: String, msg: String }, diff --git a/crates/engine/src/file_access.rs b/crates/engine/src/file_access.rs index 0565a9115f..cdea7ac5bb 100644 --- a/crates/engine/src/file_access.rs +++ b/crates/engine/src/file_access.rs @@ -208,7 +208,40 @@ pub fn check_read(path: &str) -> Result<(), String> { /// May `path` be written here? Always, without roots in force. pub fn check_write(path: &str) -> Result<(), String> { - current().map_or(Ok(()), |r| r.check(path, Access::Write)) + current().map_or(Ok(()), |r| r.check(path, Access::Write))?; + WRITES.with(|w| { + if let Some(paths) = w.borrow_mut().as_mut() + && !paths.iter().any(|(p, _)| p == path) + { + paths.push((path.to_string(), stamp(path))); + } + }); + Ok(()) +} + +/// A file's modification time and length; `None` when there is no file at `path`. +type Stamp = Option<(Option, u64)>; + +fn stamp(path: &str) -> Stamp { + std::fs::metadata(path).ok().filter(std::fs::Metadata::is_file).map(|m| (m.modified().ok(), m.len())) +} + +thread_local! { + /// The paths [`check_write`] allowed on this thread while they are being recorded, each with + /// its file's stamp at that moment. + static WRITES: std::cell::RefCell>> = const { std::cell::RefCell::new(None) }; +} + +/// Starts recording the paths [`check_write`] allows on this thread. +pub(crate) fn start_recording_writes() { + WRITES.with(|w| *w.borrow_mut() = Some(Vec::new())); +} + +/// Ends recording → the recorded paths whose file exists now: after a command that `succeeded`, +/// all of them; after one that failed, those made or changed since they were allowed. +pub(crate) fn finish_recording_writes(succeeded: bool) -> Vec { + let recorded = WRITES.with(|w| w.borrow_mut().take()).unwrap_or_default(); + recorded.into_iter().filter(|(path, before)| stamp(path).is_some_and(|now| succeeded || Some(now) != *before)).map(|(path, _)| path).collect() } /// `path` made absolute with its links followed; for a path that doesn't exist (yet), its nearest diff --git a/crates/engine/src/history.rs b/crates/engine/src/history.rs index 8df6060e02..8dced7fb9e 100644 --- a/crates/engine/src/history.rs +++ b/crates/engine/src/history.rs @@ -1,7 +1,13 @@ use super::{Arc, Document, Selection}; +#[cfg(test)] +thread_local! { + /// Tests: how many undo steps were copied on this thread. + pub(crate) static ENTRY_CLONES: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + /// One undo step. -#[derive(Clone, Debug)] +#[derive(Debug)] pub struct HistoryEntry { pub label: String, /// The document as it was. It keeps no lookup cache ([`Document::drop_lookup_cache`]): a @@ -27,6 +33,25 @@ pub struct HistoryEntry { color_mode_bytes: usize, } +impl Clone for HistoryEntry { + fn clone(&self) -> Self { + #[cfg(test)] + ENTRY_CLONES.with(|n| n.set(n.get() + 1)); + HistoryEntry { + label: self.label.clone(), + doc: self.doc.clone(), + selection: self.selection.clone(), + bytes: self.bytes, + next_bytes: self.next_bytes, + next: self.next, + named: self.named.clone(), + serial: self.serial, + color_mode_paints: self.color_mode_paints.clone(), + color_mode_bytes: self.color_mode_bytes, + } + } +} + /// The next [`HistoryEntry::serial`]: 1 for the first step made, so 0 never names a step. fn next_serial() -> u64 { static NEXT: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1); @@ -148,11 +173,52 @@ pub struct History { /// About the most memory the steps may keep ([`HistoryEntry::bytes`]): past it the oldest /// steps go, but never the last [`History::MIN_STEPS`] undo (and redo) steps. pub byte_budget: usize, + /// Counts the changes made in place to steps below the newest ([`History::put_back`]). + pub(crate) rewrites: u64, + /// Between [`History::mark`] and [`History::release`] or [`History::put_back`]. + pub(crate) held: bool, + /// The redo steps a new step cleared while held ([`History::clear_redo`]). + pub(crate) set_aside: Option>, } impl Default for History { fn default() -> Self { - History { undo: vec![], redo: vec![], limit: 0, byte_budget: default_history_budget() } + History { undo: vec![], redo: vec![], limit: 0, byte_budget: default_history_budget(), rewrites: 0, held: false, set_aside: None } + } +} + +/// What [`History::put_back`] needs to give a history back as it was when [`History::mark`] took +/// it: the newest undo and redo steps, and where each stack stood under them. It holds no other +/// step, so taking one costs the same however many the history holds. +pub(crate) struct HistoryMark { + undo: StackMark, + redo: StackMark, + limit: usize, + byte_budget: usize, + rewrites: u64, +} + +/// One stack of a [`HistoryMark`]. +struct StackMark { + len: usize, + /// [`HistoryEntry::serial`] of the step under the newest one, 0 for none. + below: u64, + newest: Option, +} + +impl StackMark { + fn of(steps: &[HistoryEntry]) -> Self { + let len = steps.len(); + StackMark { len, below: len.checked_sub(2).and_then(|i| steps.get(i)).map_or(0, |e| e.serial), newest: steps.last().cloned() } + } + + /// Puts `steps` back as they were. → `false` when a step under the newest one was removed since. + fn put_back(self, steps: &mut Vec) -> bool { + let kept = self.len.saturating_sub(1); + let intact = steps.len() >= kept && kept.checked_sub(1).is_none_or(|i| steps.get(i).is_some_and(|e| e.serial == self.below)); + steps.truncate(kept); + steps.extend(self.newest); + intact } } @@ -208,6 +274,58 @@ impl History { self.redo.drain(..n); } + /// A [`HistoryMark`] of the history now. Until [`History::release`] or [`History::put_back`], + /// [`History::trim`] lets no step go, so the steps under the newest one stay where they are, and + /// [`History::clear_redo`] sets the redo steps aside. + pub(crate) fn mark(&mut self) -> HistoryMark { + let mark = HistoryMark { + undo: StackMark::of(&self.undo), + redo: StackMark::of(&self.redo), + limit: self.limit, + byte_budget: self.byte_budget, + rewrites: self.rewrites, + }; + self.limit = usize::MAX; + self.byte_budget = usize::MAX; + self.held = true; + self.set_aside = None; + mark + } + + /// Removes the redo steps, as a new step does. While held ([`History::mark`]) the first call + /// keeps them for [`History::put_back`]. + pub(crate) fn clear_redo(&mut self) { + if self.held && self.set_aside.is_none() { + self.set_aside = Some(std::mem::take(&mut self.redo)); + } else { + self.redo.clear(); + } + } + + /// Keeps the history as it is now: the limits `mark` held back apply again. + pub(crate) fn release(&mut self, mark: &HistoryMark) { + self.held = false; + self.set_aside = None; + self.limit = mark.limit; + self.byte_budget = mark.byte_budget; + self.trim(); + } + + /// Gives the history back as it was at `mark`. → `false` when that is not possible: an undo or + /// redo step under the newest one was removed or changed in place since. + pub(crate) fn put_back(&mut self, mark: HistoryMark) -> bool { + if let Some(redo) = self.set_aside.take() { + self.redo = redo; + } + let undo = mark.undo.put_back(&mut self.undo); + let redo = mark.redo.put_back(&mut self.redo); + let intact = self.rewrites == mark.rewrites && undo && redo; + self.held = false; + self.limit = mark.limit; + self.byte_budget = mark.byte_budget; + intact + } + /// Estimate the newest undo step again, its next state now being `now` (the steps after it were /// merged into it, or an undo group extended it). It takes a new number ([`History::step`]). pub(crate) fn recost_last(&mut self, now: &Document) { diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index eaa0e7b574..d18afc87e1 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -243,6 +243,21 @@ pub struct Session { pub(crate) screens_hand_off: Option>, /// Where Data Recovery keeps its copies ([`cmd::recovery`]). pub recovery: cmd::recovery::Recovery, + /// The running script's job, while there is one: the mutation lease ([`script`]). + pub(crate) script_key: Option, + /// Stops the running script at its next instruction; the same flag for every run. + pub(crate) script_stop: vectorcraft_js::Interrupt, + /// The report of the run that ended last. + pub(crate) script_report: Option, + /// `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, + /// 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. + pub(crate) script_in_run: bool, + /// Write recovery copies of the unsaved documents before a run, and don't start without them. + pub script_copy_first: bool, /// While the active tool's actions run: their commands aren't "a command from outside the /// tool" ([`Session::after_command`]). pub(crate) in_tool_actions: bool, @@ -329,6 +344,7 @@ mod history; mod interaction; mod prefs; mod sanity; +pub mod script; mod session; #[cfg(test)] @@ -337,7 +353,7 @@ pub(crate) use command_sets::SELECTS_GIVEN_IDS; use command_sets::given_ids; pub use command_sets::{FIT_ACTIVE_ARTBOARD, ON_ACTIVE_ARTBOARD, waits_for_tool_edit}; pub use doc_state::{DocState, OpenRows, RecalledSelection}; -pub use error::{EngineError, Result}; +pub use error::{EngineError, Result, SCRIPT_BUSY}; pub use history::{History, HistoryEntry, NamedStep, default_history_budget}; pub(crate) use interaction::PreviewCopies; pub use interaction::{Interaction, LastTransform, UndoGroup, UndoScope}; diff --git a/crates/engine/src/link_watch.rs b/crates/engine/src/link_watch.rs index 6cdf5c3591..747ce91545 100644 --- a/crates/engine/src/link_watch.rs +++ b/crates/engine/src/link_watch.rs @@ -84,9 +84,9 @@ pub(crate) fn update_changed(s: &mut Session, _: &Value) -> Result { impl Session { /// Start stamping the active document's linked files on a worker thread, unless a look is - /// still running (or the build has no files to look at: the web app). + /// still running, a script is running (or the build has no files to look at: the web app). pub fn start_link_scan(&mut self) { - if self.link_scan.is_some() || cfg!(target_arch = "wasm32") { + if self.link_scan.is_some() || self.script_key.is_some() || cfg!(target_arch = "wasm32") { return; } let Some(st) = self.active() else { return }; @@ -115,10 +115,13 @@ impl Session { } } - /// Apply a finished look (`None` while there is none, or it is still running): see - /// [`Session::apply_link_stamps`]. A look whose worker ended without stamps is cleared, also - /// with `None`, so the next one can start. + /// Apply a finished look (`None` while there is none, it is still running, or a script is + /// running): see [`Session::apply_link_stamps`]. A look whose worker ended without stamps is + /// cleared, also with `None`, so the next one can start. pub fn poll_link_scan(&mut self) -> Option> { + if self.script_key.is_some() { + return None; + } self.link_scan.take_if(|scan| ended_without_stamps(scan, |ended| ended.load(Ordering::SeqCst))); let (uid, stamps) = self.link_scan.as_ref()?.0.lock().unwrap_or_else(PoisonError::into_inner).take()?; self.link_scan = None; diff --git a/crates/engine/src/prefs.rs b/crates/engine/src/prefs.rs index 603fa9028a..9ea86a21ea 100644 --- a/crates/engine/src/prefs.rs +++ b/crates/engine/src/prefs.rs @@ -31,6 +31,8 @@ pub struct Prefs { pub disable_auto_add_delete: bool, pub use_precise_cursors: bool, pub show_tool_tips: bool, + /// Other Script… warns before it runs a chosen script. + pub show_external_script_warning: bool, pub anti_aliased_artwork: bool, pub select_same_tint_percent: bool, pub show_home_screen: bool, @@ -372,6 +374,7 @@ impl Default for Prefs { disable_auto_add_delete: false, use_precise_cursors: false, show_tool_tips: true, + show_external_script_warning: true, anti_aliased_artwork: true, select_same_tint_percent: false, show_home_screen: true, diff --git a/crates/engine/src/script/mod.rs b/crates/engine/src/script/mod.rs new file mode 100644 index 0000000000..35e93c1ad7 --- /dev/null +++ b/crates/engine/src/script/mod.rs @@ -0,0 +1,1221 @@ +//! Running a script: `script.run`, `script.stop` and the job behind them. +//! +//! A run works on its own copy of the open documents and the session state commands change (the +//! working copy). Between two slices of a run, the session holds the state as it was before the +//! run: what is drawn, what a read-only command returns and what Data Recovery copies never show a +//! script's unfinished work. Each slice swaps the working copy in, advances the interpreter by one +//! measured slice of fuel and swaps it out. A commit makes the working copy the session's state, +//! with one undo step for each document whose art changed. A rollback drops the working copy. +//! +//! While a job exists, [`Session::execute`] refuses any command that can edit, select, save or give +//! a document a new revision, and the tool events are refused the same way (the mutation lease). +//! The script's own commands run through [`Session::execute`] inside a slice, each with its own +//! parameter checks, enabled rule, undo history and journal entry, and a command that fails leaves +//! no trace of itself. Inside a run, `edit.undo` reaches only steps the script made. +//! +//! Files a script's commands saved or exported before it failed stay written, and the failure names +//! them. Ids given out in a run are never given out again for a document, also after an in-run +//! undo or a rollback. +//! +//! The values here are VectorCraft's own limits: [`MAX_SOURCE_BYTES`], [`DEFAULT_FUEL`], +//! [`MAX_FUEL`], [`SLICE_FUEL`], [`HEAP_BYTES`], [`MAX_HOST_CALLS`], [`GROWTH_OBJECTS`], +//! [`GROWTH_BYTES`], [`MAX_CONTINUES`], [`MAX_LOG_LINES`], [`MAX_LOG_BYTES`], [`MAX_ARGS_BYTES`], +//! and the 64 levels, 16 MiB and 1,048,576 entries of [`vectorcraft_js::DataLimits`]'s default. + +use std::cell::{Cell, RefCell}; +use std::collections::HashMap; +use std::rc::Rc; +use std::sync::Arc; + +use serde_json::{Map, Value, json}; +use vectorcraft_js::{ + Data, DataLimits, HostError, HostFunction, HostItem, Interrupt, LimitKind, Limits, Options, Progress, Realm, RunError, RunErrorKind, +}; + +use crate::{ + Clipboard, DocState, DrawMode, EngineError, Journal, NodeId, PaintDefaults, Result, Session, cmd, command_specs, guard, waits_for_tool_edit, +}; + +/// The most bytes of source a run takes, as a file or as `source`. +pub const MAX_SOURCE_BYTES: usize = 8 << 20; +/// The instructions a run may execute when `maxFuel` is left out. +pub const DEFAULT_FUEL: u64 = 1_000_000_000; +/// The largest `maxFuel`. +pub const MAX_FUEL: u64 = 100_000_000_000; +/// The instructions one slice of a run executes before the interface draws again. +pub const SLICE_FUEL: u64 = 500_000; +/// The heap one run may use. +#[cfg(not(target_arch = "wasm32"))] +pub const HEAP_BYTES: usize = 256 << 20; +/// The heap one run may use in a wasm build. +#[cfg(target_arch = "wasm32")] +pub const HEAP_BYTES: usize = 128 << 20; +/// The most `vc.run` calls and getter reads of one run. +pub const MAX_HOST_CALLS: u64 = 2_000_000; +/// The objects a run may make before it is asked to continue or stop. +pub const GROWTH_OBJECTS: u64 = 100_000; +/// The bytes of new document data a run may keep before it is asked to continue or stop. +pub const GROWTH_BYTES: u64 = 512 << 20; +/// How many times a person may let a run go past its growth allowance; each time adds one more. +pub const MAX_CONTINUES: u32 = 8; +/// The most `vc.log` entries of one run. +pub const MAX_LOG_LINES: usize = 10_000; +/// The most bytes of `vc.log` entries of one run. +pub const MAX_LOG_BYTES: usize = 4 << 20; +/// The most bytes of `args` given to one run, as JSON. +pub const MAX_ARGS_BYTES: usize = 1 << 20; +/// The `vc.run` calls one slice makes before the interface draws again. +const SLICE_HOST_CALLS: u32 = 256; +/// The bytes that may cross between a script and the host in one run. +const MAX_BRIDGE_BYTES: u64 = 4 << 30; + +/// The version `vc.api.version` gives. +pub const API_VERSION: &str = "1.0"; +/// The features `vc.api.has` knows. +pub const API_FEATURES: &[&str] = &["run", "document", "commands", "log", "args"]; + +/// What the step of a run's one undo step is called. +pub const STEP_LABEL: &str = "Run Script"; + +/// `id`, as `vc.run` is given it, is one a script may not run: a command that would leave the run's +/// transaction, change something outside the documents that a rollback could not put back, or clear +/// the undo steps from before the run, which the run keeps. +pub fn refused_to_scripts(id: &str) -> bool { + const PREFIXES: &[&str] = &[ + "script.", + "plugin.", + "prefs.", + "actionSet.", + "shortcutSet.", + "help.", + "print.", + "library.", + "importMatches.", + "edit.undoGroup.", + "file.recovery.", + "stroke.widthProfile.", + ]; + const IDS: &[&str] = &[ + "text.addFontFiles", + "text.findFontFiles", + "text.rescanFonts", + "links.findFiles", + "file.place.queue", + "color.loadProfile", + "color.removeProfile", + "file.print", + "view.proofSetup", + "view.proofColors", + "view.overprintPreview", + "view.separationsPreview", + "edit.clearHistory", + ]; + let saved_preset = (id.contains("resets.") || id.contains(".preset.")) && !id.ends_with(".list") && !id.ends_with(".apply"); + id != "script.check" && (saved_preset || PREFIXES.iter().any(|p| id.starts_with(p)) || IDS.contains(&id)) +} + +/// The error for a script's command that [`refused_to_scripts`] names. +pub(crate) fn refused_text(id: &str) -> String { + format!("a script cannot run `{id}`") +} + +/// A request to run a script. +pub(crate) struct Request { + pub name: String, + pub source: String, + pub args: Map, + pub fuel: u64, +} + +thread_local! { + /// The running jobs of this thread's sessions. A job is held here, and not in its session, + /// because it holds the interpreter, which stays on the thread that started it. + static JOBS: RefCell> = RefCell::new(HashMap::new()); +} + +static NEXT_JOB: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1); + +/// A session's hold on its running job: while one exists the lease is held. Dropping it ends the job. +#[derive(Debug)] +pub struct JobKey(u64); + +impl Drop for JobKey { + fn drop(&mut self) { + let _ = JOBS.try_with(|jobs| { + if let Ok(mut jobs) = jobs.try_borrow_mut() { + jobs.remove(&self.0); + } + }); + } +} + +fn with_job(key: &JobKey, f: impl FnOnce(&mut Job) -> T) -> Option { + JOBS.with(|jobs| jobs.borrow_mut().get_mut(&key.0).map(f)) +} + +/// The state a script changes that a rollback puts back. +struct World { + docs: Vec, + active: Option, + paint: PaintDefaults, + fill_active: bool, + draw_mode: DrawMode, + draw_inside: Option, + clipboard: Clipboard, + untitled_counter: u32, + menu: cmd::menucmds::MenuState, + last_solid: crate::Color, + last_gradient: crate::GradientPaint, + recent_colors: Vec, + pending_paint: Option, + choices: Choices, + journal: Journal, + /// The preferences when the run started. + start_prefs: crate::Prefs, + /// The Caps Lock state when the run started. + start_caps_lock: bool, +} + +/// The choices outside the documents that a script's commands can change: the preferences, the +/// global edit options, the recent URLs, the chosen gradient stop, freeform point and appearance +/// item, the Eyedropper's sample, the envelope defaults and the Caps Lock state. +#[derive(Clone)] +struct Choices { + prefs: crate::Prefs, + caps_lock: bool, + eyedropper_sample: Option>, + global_edit_options: cmd::globaledit::Options, + recent_urls: Vec, + gradient_stop: Option<(usize, cmd::gradient::StopOwner)>, + freeform_point: Option<(usize, cmd::gradient::StopOwner)>, + active_appearance_item: Option, + envelope_defaults: Option<(vectorcraft_doc::live::EnvelopeOptions, f64)>, +} + +impl Choices { + fn of(s: &Session) -> Self { + Self { + prefs: s.prefs.clone(), + caps_lock: s.caps_lock, + eyedropper_sample: s.eyedropper_sample.clone(), + global_edit_options: s.global_edit_options.clone(), + recent_urls: s.recent_urls.clone(), + gradient_stop: s.gradient_stop, + freeform_point: s.freeform_point, + active_appearance_item: s.active_appearance_item.clone(), + envelope_defaults: s.envelope_defaults, + } + } + + fn put(self, s: &mut Session) { + s.prefs = self.prefs; + s.caps_lock = self.caps_lock; + s.eyedropper_sample = self.eyedropper_sample; + s.global_edit_options = self.global_edit_options; + s.recent_urls = self.recent_urls; + s.gradient_stop = self.gradient_stop; + s.freeform_point = self.freeform_point; + s.active_appearance_item = self.active_appearance_item; + s.envelope_defaults = self.envelope_defaults; + } + + fn swap(&mut self, s: &mut Session) { + use std::mem::swap; + swap(&mut self.prefs, &mut s.prefs); + swap(&mut self.caps_lock, &mut s.caps_lock); + swap(&mut self.eyedropper_sample, &mut s.eyedropper_sample); + swap(&mut self.global_edit_options, &mut s.global_edit_options); + swap(&mut self.recent_urls, &mut s.recent_urls); + swap(&mut self.gradient_stop, &mut s.gradient_stop); + swap(&mut self.freeform_point, &mut s.freeform_point); + swap(&mut self.active_appearance_item, &mut s.active_appearance_item); + swap(&mut self.envelope_defaults, &mut s.envelope_defaults); + } +} + +/// The preferences after a run: `current`, the session's, which the app may have changed while the +/// run went on, with each preference the run changed from `start` set to the run's value. +fn merged_prefs(start: &crate::Prefs, run: &crate::Prefs, current: &crate::Prefs) -> crate::Prefs { + let (Ok(Value::Object(start)), Ok(Value::Object(run)), Ok(Value::Object(mut out))) = + (serde_json::to_value(start), serde_json::to_value(run), serde_json::to_value(current)) + else { + return current.clone(); + }; + for (key, value) in run { + if start.get(&key) != Some(&value) { + out.insert(key, value); + } + } + serde_json::from_value(Value::Object(out)).unwrap_or_else(|_| current.clone()) +} + +impl World { + /// A working copy of the session's state: its documents, each with an undo history of its own + /// that starts empty, and an empty journal. + fn working(s: &Session) -> Self { + let mut docs = s.docs.clone(); + for st in &mut docs { + st.history.undo.clear(); + st.history.redo.clear(); + } + Self { + docs, + active: s.active, + paint: s.paint.clone(), + fill_active: s.fill_active, + draw_mode: s.draw_mode, + draw_inside: s.draw_inside, + clipboard: s.clipboard.clone(), + untitled_counter: s.untitled_counter, + menu: s.menu.clone(), + last_solid: s.last_solid, + last_gradient: s.last_gradient.clone(), + recent_colors: s.recent_colors.clone(), + pending_paint: s.pending_paint.clone(), + choices: Choices::of(s), + journal: Journal::default(), + start_prefs: s.prefs.clone(), + start_caps_lock: s.caps_lock, + } + } + + /// Exchanges this state with the session's. + fn swap(&mut self, s: &mut Session) { + use std::mem::swap; + swap(&mut self.docs, &mut s.docs); + swap(&mut self.active, &mut s.active); + swap(&mut self.paint, &mut s.paint); + swap(&mut self.fill_active, &mut s.fill_active); + swap(&mut self.draw_mode, &mut s.draw_mode); + swap(&mut self.draw_inside, &mut s.draw_inside); + swap(&mut self.clipboard, &mut s.clipboard); + swap(&mut self.untitled_counter, &mut s.untitled_counter); + swap(&mut self.menu, &mut s.menu); + swap(&mut self.last_solid, &mut s.last_solid); + swap(&mut self.last_gradient, &mut s.last_gradient); + swap(&mut self.recent_colors, &mut s.recent_colors); + swap(&mut self.pending_paint, &mut s.pending_paint); + self.choices.swap(s); + swap(&mut self.journal, &mut s.journal); + } +} + +/// The commands that can change the clipboard and still fail, and that do not put it back +/// themselves. The clipboard can hold a great deal, so a savepoint copies it only for these. +const CAN_FAIL_AFTER_COPYING: &[&str] = &["action.batch", "edit.cut"]; + +/// The commands that remove a document's undo history, or the document: a savepoint keeps a whole +/// copy of the histories for these. Any other command that removes or changes a step under the +/// newest undo or redo step and then fails ends the run ([`HISTORY_LOST`]). +const DROP_HISTORY: &[&str] = &["file.close", "file.closeAll", "document.close", "file.revert"]; + +/// A document's state before a command: everything but its undo history, which `mark` gives back, +/// or `whole` for the commands in [`DROP_HISTORY`]. +struct SavedDoc { + state: DocState, + mark: crate::history::HistoryMark, + whole: Option, +} + +/// What one command may need to put back when it fails inside a run: the state of [`World`] the +/// command can reach. +pub(crate) struct Savepoint { + docs: Vec, + active: Option, + paint: PaintDefaults, + fill_active: bool, + draw_mode: DrawMode, + draw_inside: Option, + clipboard: Option, + untitled_counter: u32, + menu: cmd::menucmds::MenuState, + last_solid: crate::Color, + last_gradient: crate::GradientPaint, + recent_colors: Vec, + pending_paint: Option, + choices: Choices, + journal: usize, +} + +impl Savepoint { + /// The state before command `id`. Until [`Savepoint::keep`] or [`Savepoint::restore`], the + /// documents' undo histories let no step go. + pub(crate) fn take(s: &mut Session, id: &str) -> Self { + let whole = DROP_HISTORY.contains(&id); + let docs = s + .docs + .iter_mut() + .map(|st| { + let history = std::mem::take(&mut st.history); + let state = st.clone(); + st.history = history; + let whole = whole.then(|| st.history.clone()); + SavedDoc { state, mark: st.history.mark(), whole } + }) + .collect(); + Self { + docs, + active: s.active, + paint: s.paint.clone(), + fill_active: s.fill_active, + draw_mode: s.draw_mode, + draw_inside: s.draw_inside, + clipboard: CAN_FAIL_AFTER_COPYING.contains(&id).then(|| s.clipboard.clone()), + untitled_counter: s.untitled_counter, + menu: s.menu.clone(), + last_solid: s.last_solid, + last_gradient: s.last_gradient.clone(), + recent_colors: s.recent_colors.clone(), + pending_paint: s.pending_paint.clone(), + choices: Choices::of(s), + journal: s.journal.len(), + } + } + + /// Keeps what the command did: the histories' limits apply again. + pub(crate) fn keep(self, s: &mut Session) { + for saved in &self.docs { + if let Some(st) = s.docs.iter_mut().find(|d| d.uid == saved.state.uid) { + st.history.release(&saved.mark); + } + } + } + + /// Puts back the state before the command. → `false` when an undo history could not be given + /// back as it was (a step under the newest one was removed or changed in place, or its + /// document was closed); the rest is put back all the same. + pub(crate) fn restore(self, s: &mut Session) -> bool { + let mut exact = true; + let mut docs = Vec::with_capacity(self.docs.len()); + for SavedDoc { mut state, mark, whole } in self.docs { + let now = s.docs.iter_mut().find(|d| d.uid == state.uid).map(|d| std::mem::take(&mut d.history)); + state.history = match (whole, now) { + (Some(history), _) => history, + (None, Some(mut history)) => { + exact &= history.put_back(mark); + history + } + (None, None) => { + exact = false; + let mut history = crate::History::default(); + history.put_back(mark); + history + } + }; + docs.push(state); + } + s.docs = docs; + s.active = self.active; + s.paint = self.paint; + s.fill_active = self.fill_active; + s.draw_mode = self.draw_mode; + s.draw_inside = self.draw_inside; + if let Some(clipboard) = self.clipboard { + s.clipboard = clipboard; + } + s.untitled_counter = self.untitled_counter; + s.menu = self.menu; + s.last_solid = self.last_solid; + s.last_gradient = self.last_gradient; + s.recent_colors = self.recent_colors; + s.pending_paint = self.pending_paint; + self.choices.put(s); + s.journal.truncate(self.journal); + exact + } +} + +/// The counters and the session a script's host functions share. Between slices `session` holds a +/// spare session; during a slice it holds the real one, because the interpreter cannot be given a +/// borrow of it. +struct Host { + session: Rc>, + pause: Rc>, + /// The run is sliced by frames, so the person at the computer can be asked to continue. + framed: bool, + calls: Cell, + calls_this_slice: Cell, + objects: Cell, + bytes_kept: Cell, + bridge: Cell, + allowance_objects: Cell, + allowance_bytes: Cell, + continues: Cell, + /// Past the growth allowance, waiting for the person's answer. + waiting: Cell, + log: RefCell>, + log_bytes: Cell, + written: RefCell>, +} + +impl Host { + fn over(&self, limit: &str) -> HostError { + HostError::Abort(limit.to_string()) + } + + fn charge_call(&self, bytes: u64) -> std::result::Result<(), HostError> { + let calls = self.calls.get() + 1; + self.calls.set(calls); + if calls > MAX_HOST_CALLS { + return Err(self.over(OVER_CALLS)); + } + let bridge = self.bridge.get().saturating_add(bytes); + self.bridge.set(bridge); + if bridge > MAX_BRIDGE_BYTES { + return Err(self.over(OVER_BRIDGE)); + } + let n = self.calls_this_slice.get() + 1; + self.calls_this_slice.set(n); + if n >= SLICE_HOST_CALLS { + self.pause.set(true); + } + Ok(()) + } + + /// Counts what a command added to the documents, past which the person is asked or, without + /// anyone to ask, the run ends. A run that goes on past twice its allowance within one slice + /// ends too. + fn charge_growth(&self, objects: u64, bytes: u64) -> std::result::Result<(), HostError> { + self.objects.set(self.objects.get().saturating_add(objects)); + self.bytes_kept.set(self.bytes_kept.get().saturating_add(bytes)); + let (o, b) = (self.objects.get(), self.bytes_kept.get()); + let (limit_o, limit_b) = (self.allowance_objects.get(), self.allowance_bytes.get()); + if o <= limit_o && b <= limit_b { + return Ok(()); + } + let may_ask = self.framed && self.continues.get() < MAX_CONTINUES; + if !may_ask || o > limit_o.saturating_mul(2) || b > limit_b.saturating_mul(2) { + return Err(self.over(OVER_GROWTH)); + } + self.waiting.set(true); + self.pause.set(true); + Ok(()) + } +} + +/// A run in progress. +struct Job { + realm: Realm, + host: Rc, + /// Between slices the working copy; during the last slice's commit the state before the run. + world: World, + /// The documents open when the run began, by [`DocState::uid`]. + start_uids: Vec, + name: String, +} + +/// The `Data` for a JSON value, within `limits`. When it does not fit, the error is the place in +/// `v` where it stopped fitting, such as `.layers[2].name`, and empty for `v` itself. +pub(crate) fn to_data(v: &Value, limits: &DataLimits, depth: usize, used: &mut (usize, usize)) -> std::result::Result { + if depth > limits.depth { + return Err(String::new()); + } + used.0 = used.0.saturating_add(16); + used.1 = used.1.saturating_add(1); + if used.0 > limits.bytes || used.1 > limits.entries { + return Err(String::new()); + } + Ok(match v { + Value::Null => Data::Null, + Value::Bool(b) => Data::Bool(*b), + Value::Number(n) => Data::Number(n.as_f64().unwrap_or(f64::NAN)), + Value::String(s) => { + used.0 = used.0.saturating_add(s.len()); + if used.0 > limits.bytes { + return Err(String::new()); + } + Data::String(s.clone()) + } + Value::Array(a) => Data::Array( + a.iter() + .enumerate() + .map(|(i, x)| to_data(x, limits, depth + 1, used).map_err(|place| format!("[{i}]{place}"))) + .collect::>()?, + ), + Value::Object(o) => Data::Object( + o.iter() + .map(|(k, x)| { + used.0 = used.0.saturating_add(k.len()); + to_data(x, limits, depth + 1, used).map(|d| (k.clone(), d)).map_err(|place| format!(".{k}{place}")) + }) + .collect::>()?, + ), + }) +} + +/// The JSON for a value a script gave; a whole number within a double's exact range is an integer, +/// which is how commands read ids and counts. +fn to_json(d: &Data) -> Value { + match d { + Data::Undefined | Data::Null => Value::Null, + Data::Bool(b) => Value::Bool(*b), + Data::Number(n) => + { + #[allow(clippy::cast_possible_truncation)] + if n.fract() == 0.0 && n.abs() <= 9_007_199_254_740_992.0 { + json!(*n as i64) + } else { + serde_json::Number::from_f64(*n).map_or(Value::Null, Value::Number) + } + } + Data::String(s) => Value::String(s.clone()), + Data::Array(a) => Value::Array(a.iter().map(to_json).collect()), + Data::Object(o) => Value::Object(o.iter().map(|(k, v)| (k.clone(), to_json(v))).collect()), + } +} + +/// A step into a JSON value: a key or an index. +enum Step<'a> { + Name(&'a str), + Index(usize), +} + +/// The place in `v` that is more than [`DataLimits`]' depth levels deep, such as `.layers[2].name`, +/// or `None`. It walks `v` with a list of its own, so any depth fits on the stack. +pub(crate) fn too_deep(v: &Value) -> Option { + let limit = DataLimits::default().depth; + // `steps[i - 1]` is the entry that holds entry `i` and the step into it; entry 0 is `v`. + let mut steps: Vec<(usize, Step<'_>)> = Vec::new(); + let mut todo = vec![(v, 0usize, 0usize)]; + while let Some((v, depth, entry)) = todo.pop() { + if depth > limit { + let mut place = Vec::new(); + let mut at = entry; + while let Some((parent, step)) = at.checked_sub(1).and_then(|i| steps.get(i)) { + place.push(match step { + Step::Name(k) => format!(".{k}"), + Step::Index(i) => format!("[{i}]"), + }); + at = *parent; + } + place.reverse(); + return Some(place.concat()); + } + let children: Box, &Value)>> = match v { + Value::Array(a) => Box::new(a.iter().enumerate().map(|(i, x)| (Step::Index(i), x))), + Value::Object(o) => Box::new(o.iter().map(|(k, x)| (Step::Name(k.as_str()), x))), + _ => continue, + }; + for (step, child) in children { + steps.push((entry, step)); + todo.push((child, depth + 1, steps.len())); + } + } + None +} + +/// Estimated bytes of `d`. +fn data_size(d: &Data) -> u64 { + match d { + Data::Undefined | Data::Null | Data::Bool(_) => 4, + Data::Number(_) => 8, + Data::String(s) => s.len() as u64 + 2, + Data::Array(a) => 8 + a.iter().map(data_size).sum::(), + Data::Object(o) => 8 + o.iter().map(|(k, v)| k.len() as u64 + 2 + data_size(v)).sum::(), + } +} + +/// Brings each open document's next id up to the highest one the session has given out for it. +fn raise_ids(s: &mut Session) { + let marks = std::mem::take(&mut s.script_high_water); + for st in &mut s.docs { + if let Some(&mark) = marks.get(&st.uid) + && mark > st.doc.peek_next_id() + { + st.change_unsaved(|d| Arc::make_mut(d).raise_next_id(mark)); + } + } + s.script_high_water = marks; +} + +/// Every object in `d`: all its art ([`crate::Document::art_roots`]), opacity masks included. +fn all_objects(d: &crate::Document) -> u64 { + d.art_roots().map(|n| n.count_with_masks() as u64).sum() +} + +fn note_ids(s: &mut Session) { + for st in &s.docs { + let mark = s.script_high_water.entry(st.uid).or_insert(0); + *mark = (*mark).max(st.doc.peek_next_id()); + } +} + +/// Runs command `id` inside a slice. A command that fails puts everything back it had done. +/// → its result, the objects it added, the bytes of document data it added and the state before +/// it, for a result that cannot cross to the script. +fn step(s: &mut Session, host: &Host, id: &str, params: &Value) -> Result<(Value, u64, u64, Option)> { + raise_ids(s); + let mutating = waits_for_tool_edit(id); + let save = mutating.then(|| Savepoint::take(s, id)); + let before: Vec<(u64, Arc, u64)> = + if mutating { s.docs.iter().map(|d| (d.uid, d.doc.clone(), d.doc.peek_next_id())).collect() } else { Vec::new() }; + crate::file_access::start_recording_writes(); + let r = s.execute(id, params); + // A file a command wrote before it failed is on disk all the same. + let mut written = host.written.borrow_mut(); + for path in crate::file_access::finish_recording_writes(r.is_ok()) { + if !written.contains(&path) { + written.push(path); + } + } + drop(written); + match r { + Ok(v) => { + note_ids(s); + let (mut objects, mut bytes) = (0, 0); + for st in &s.docs { + match before.iter().find(|(uid, ..)| *uid == st.uid) { + Some((_, d, ids)) if !Arc::ptr_eq(d, &st.doc) => { + objects += st.doc.peek_next_id().saturating_sub(*ids); + bytes += d.retained_bytes_each(&st.doc).1 as u64; + } + Some(_) => {} + // A document the command opened or made counts whole. + None if mutating => { + objects += all_objects(&st.doc); + bytes += crate::Document::new(1.0, 1.0).retained_bytes_each(&st.doc).1 as u64; + } + None => {} + } + } + Ok((v, objects, bytes, save)) + } + Err(e) => { + if let Some(save) = save + && !save.restore(s) + { + return Err(EngineError::Internal { cmd: id.to_string(), msg: HISTORY_LOST.to_string() }); + } + Err(e) + } + } +} + +fn vc_run(host: &Rc, args: Vec) -> std::result::Result { + let Some(Data::String(id)) = args.first() else { return Err(HostError::Type(NO_COMMAND_ID.to_string())) }; + if args.len() > 2 { + return Err(HostError::Type(TOO_MANY_ARGUMENTS.to_string())); + } + let id = id.clone(); + let params = match args.get(1) { + None | Some(Data::Undefined) => json!({}), + Some(d @ Data::Object(_)) => to_json(d), + Some(_) => return Err(HostError::Type(PARAMS_NOT_OBJECT.to_string())), + }; + let bytes = args.iter().map(data_size).sum(); + host.charge_call(bytes)?; + let session = host.session.clone(); + let r = { + let mut s = session.borrow_mut(); + step(&mut s, host, &id, ¶ms) + }; + let (value, objects, added, save) = match r { + Ok(done) => done, + // A bug is not something a script can handle, and neither is a request to stop. + Err(e @ EngineError::Internal { .. }) => return Err(HostError::Abort(e.to_string())), + Err(EngineError::Cancelled) => return Err(HostError::Abort("canceled".into())), + Err(e) => return Err(HostError::Error(e.to_string())), + }; + let crossed = host.charge_growth(objects, added).and_then(|()| { + let data = to_data(&value, &result_limits(), 0, &mut (0, 0)) + .map_err(|place| HostError::Range(format!("vc.run: the result{place} is too large for a script")))?; + host.charge_call(data_size(&data))?; + Ok(data) + }); + // A command whose result does not reach the script is put back, like one that failed. + if let Some(save) = save { + let mut s = session.borrow_mut(); + if crossed.is_ok() { + save.keep(&mut s); + } else if !save.restore(&mut s) { + return Err(HostError::Abort(HISTORY_LOST.to_string())); + } + } + crossed +} + +/// A bounded snapshot of the active document, or `null` with none open. A snapshot past the limits +/// of a crossing throws a `RangeError`. +fn vc_document(host: &Host) -> std::result::Result { + let s = host.session.borrow(); + let Some(st) = s.active() else { return Ok(Data::Null) }; + let ids: Vec = st.selection.objects.iter().take(1_000).map(|i| i.0).collect(); + let v = json!({ + "name": st.title(), + "path": st.path, + "modified": st.is_dirty(), + "artboards": st.doc.artboards.len(), + "layers": st.doc.layers.len(), + "selection": ids, + "selectionCount": st.selection.objects.len(), + }); + to_data(&v, &DataLimits::default(), 0, &mut (0, 0)).map_err(|place| HostError::Range(format!("vc.document{place} is too large for a script"))) +} + +/// Every command a script may run: its id, label and parameters. +fn vc_commands() -> Data { + Data::Array( + command_specs() + .iter() + .filter(|c| !refused_to_scripts(c.id)) + .map(|c| { + Data::Object(vec![ + ("id".into(), Data::String(c.id.into())), + ("label".into(), Data::String(c.label.into())), + ("params".into(), Data::String(c.params.into())), + ]) + }) + .collect(), + ) +} + +fn vc_log(host: &Host, args: Vec) -> std::result::Result { + let entry = args.first().unwrap_or(&Data::Undefined); + let bytes = data_size(entry) as usize; + if host.log.borrow().len() >= MAX_LOG_LINES || host.log_bytes.get().saturating_add(bytes) > MAX_LOG_BYTES { + return Err(HostError::Range(LOG_FULL.to_string())); + } + host.log_bytes.set(host.log_bytes.get() + bytes); + host.log.borrow_mut().push(to_json(entry)); + Ok(Data::Undefined) +} + +fn function(f: impl Fn(Vec) -> std::result::Result + 'static) -> HostFunction { + Rc::new(f) +} + +fn vc_object(host: &Rc, args: Data) -> Vec<(String, HostItem)> { + let run = { + let h = host.clone(); + function(move |a| vc_run(&h, a)) + }; + let document = { + let h = host.clone(); + function(move |_| { + h.charge_call(64)?; + vc_document(&h) + }) + }; + let commands = { + let h = host.clone(); + let list = Rc::new(vc_commands()); + let size = data_size(&list); + function(move |_| { + h.charge_call(size)?; + Ok((*list).clone()) + }) + }; + let log = { + let h = host.clone(); + function(move |a| { + h.charge_call(data_size(a.first().unwrap_or(&Data::Undefined)))?; + vc_log(&h, a) + }) + }; + let has = function(|a| Ok(Data::Bool(matches!(a.first(), Some(Data::String(f)) if API_FEATURES.contains(&f.as_str()))))); + vec![ + ("run".into(), HostItem::Function(run)), + ("document".into(), HostItem::Getter(document)), + ("commands".into(), HostItem::Getter(commands)), + ("log".into(), HostItem::Function(log)), + ("args".into(), HostItem::Value(args)), + ( + "api".into(), + HostItem::Object(vec![("version".into(), HostItem::Value(Data::String(API_VERSION.into()))), ("has".into(), HostItem::Function(has))]), + ), + ] +} + +/// A plain-words kind of a run's failure, as the report gives it. +fn kind_id(kind: &RunErrorKind) -> &'static str { + match kind { + RunErrorKind::Syntax => "syntax", + RunErrorKind::Thrown => "thrown", + RunErrorKind::Limit(LimitKind::Interrupted) => "stopped", + RunErrorKind::Limit(_) => "limit", + RunErrorKind::Internal => "internal", + } +} + +/// `message`, with what to do about a failure that comes from a script written for another program. +fn explained(kind: &RunErrorKind, message: &str, source: &str, line: u32) -> String { + const HOST_OBJECTS: &[&str] = + &["app", "$", "alert", "confirm", "prompt", "File", "Folder", "Window", "BridgeTalk", "activeDocument", "documents"]; + let names_host_object = + message.strip_prefix("ReferenceError: ").is_some_and(|m| HOST_OBJECTS.iter().any(|o| m.split_whitespace().next() == Some(o))); + let directive = + *kind == RunErrorKind::Syntax && line > 0 && source.lines().nth(line as usize - 1).is_some_and(|l| l.trim_start().starts_with('#')); + if *kind == RunErrorKind::Thrown && names_host_object { + format!("{message} (scripts here use the `vc` object; objects other applications give their scripts are not available)") + } else if directive { + format!("{message} (preprocessor lines such as `#target` and `#include` are not read yet)") + } else { + message.to_string() + } +} + +impl Session { + /// Is a script running? While one is, the commands that change anything are refused. + pub fn script_running(&self) -> bool { + self.script_key.is_some() + } + + /// The flag that stops the script running in this session from any thread, at its next + /// instruction. + pub fn script_interrupt(&self) -> Interrupt { + self.script_stop.clone() + } + + /// The report of the run that ended last (`script.run`'s result, or its failure). + pub fn script_report(&self) -> Option<&Value> { + self.script_report.as_ref() + } + + /// The error text of the last run when it failed: its name, place, message and kind, and the + /// files it left written. + pub fn script_failure_text(&self) -> Option { + self.script_report.as_ref().filter(|r| r["ok"] == false).map(failure_text) + } + + /// Has the running script used up its growth allowance, so a person must answer? A run asked + /// to stop no longer waits: the next [`Session::script_pump`] ends it. + pub fn script_waiting(&self) -> bool { + !self.script_stop.is_set() && self.script_key.as_ref().and_then(|k| with_job(k, |j| j.host.waiting.get())).unwrap_or(false) + } + + /// The name of the running script. + pub fn script_name(&self) -> Option { + self.script_key.as_ref().and_then(|k| with_job(k, |j| j.name.clone())) + } + + /// Lets the run go past its growth allowance by one more allowance. + pub fn script_continue(&mut self) { + if let Some(k) = &self.script_key { + with_job(k, |j| { + let h = &j.host; + if h.waiting.replace(false) { + h.continues.set(h.continues.get() + 1); + h.allowance_objects.set(h.allowance_objects.get().saturating_add(growth_objects())); + h.allowance_bytes.set(h.allowance_bytes.get().saturating_add(GROWTH_BYTES)); + } + }); + } + } + + /// Asks the running script to stop; it is rolled back at the next slice. False with none running. + pub fn script_request_stop(&mut self) -> bool { + if self.script_key.is_none() { + return false; + } + self.script_stop.set(); + true + } + + /// 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 { + let Some(key) = self.script_key.take() else { return false }; + let Some(job) = JOBS.with(|jobs| jobs.borrow_mut().remove(&key.0)) else { + drop(key); + raise_ids(self); + self.script_stop.clear(); + self.reset_tool(); + cmd::compositefonts::sync(self); + return true; + }; + drop(key); + let kind = LimitKind::Interrupted; + let e = RunError { kind: RunErrorKind::Limit(kind), message: format!("limit reached: {kind:?}"), line: 0, column: 0 }; + let _ = self.script_failed(job, &e); + true + } + + /// 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<()> { + self.finish_tool_edit_later()?; + if self.active().is_some() { + cmd::settle_interaction(self)?; + } + if self.explicit_undo_group.is_some() || self.docs.iter().any(|d| d.undo_group.is_some() || d.interaction.is_some()) { + return Err(EngineError::Other(OPEN_EDIT.to_string())); + } + Ok(()) + } + + /// Begins a run of `request`. + pub(crate) fn script_start(&mut self, request: Request) -> Result<()> { + self.settle_for_script()?; + // In a build where a fault ends the program, every unsaved document has a copy first. + if self.script_copy_first && self.docs.iter().any(DocState::is_dirty) && cmd::recovery::save_copies(self).is_err() { + return Err(EngineError::Other(NO_RECOVERY_COPY.to_string())); + } + self.reset_tool(); + let open: Vec = self.docs.iter().map(|d| d.uid).collect(); + self.script_high_water.retain(|uid, _| open.contains(uid)); + self.script_stop.clear(); + self.script_report = None; + let limits = Limits { fuel: request.fuel, heap_bytes: HEAP_BYTES, ..Limits::default() }; + let options = Options { max_source_units: MAX_SOURCE_BYTES.saturating_mul(2), ..Options::default() }; + let mut realm = Realm::with_options(options, limits); + realm.share_interrupt(&self.script_stop); + realm.set_data_limits(DataLimits::default()); + let host = Rc::new(Host { + session: Rc::new(RefCell::new(Session::new())), + pause: realm.pause_flag(), + framed: self.script_frames, + calls: Cell::new(0), + calls_this_slice: Cell::new(0), + objects: Cell::new(0), + bytes_kept: Cell::new(0), + bridge: Cell::new(0), + allowance_objects: Cell::new(growth_objects()), + allowance_bytes: Cell::new(GROWTH_BYTES), + continues: Cell::new(0), + waiting: Cell::new(false), + log: RefCell::new(Vec::new()), + log_bytes: Cell::new(0), + written: RefCell::new(Vec::new()), + }); + let args = to_data(&Value::Object(request.args), &DataLimits::default(), 0, &mut (0, 0)) + .map_err(|place| EngineError::BadParams { cmd: "script.run".into(), msg: format!("`args{place}` is nested more than 64 levels deep") })?; + let started = realm.define_host_object("vc", vc_object(&host, args)).and_then(|()| realm.start(&request.source)); + if let Err(e) = started { + let report = failure_report(&request.name, &e, &request.source, &host, 0); + let message = failure_text(&report); + self.script_report = Some(report); + return Err(EngineError::Other(message)); + } + let job = Job { realm, host, world: World::working(self), start_uids: open, name: request.name }; + let id = NEXT_JOB.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + JOBS.with(|jobs| jobs.borrow_mut().insert(id, job)); + self.script_key = Some(JobKey(id)); + Ok(()) + } + + /// 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. + pub fn script_pump(&mut self) -> Option> { + let key = self.script_key.take()?; + let Some(mut job) = JOBS.with(|jobs| jobs.borrow_mut().remove(&key.0)) else { + return Some(Err(EngineError::Other(JOB_GONE.to_string()))); + }; + if job.host.waiting.get() && !self.script_stop.is_set() { + JOBS.with(|jobs| jobs.borrow_mut().insert(key.0, job)); + self.script_key = Some(key); + return None; + } + if vectorcraft_doc::cancel::check().is_err() { + self.script_stop.set(); + } + job.host.calls_this_slice.set(0); + let outcome = run_slice(self, &mut job); + match outcome { + Err(panic) => { + let e = RunError { kind: RunErrorKind::Internal, message: panic, line: 0, column: 0 }; + Some(self.script_failed(job, &e)) + } + Ok(Err(e)) => Some(self.script_failed(job, &e)), + Ok(Ok(Progress::Paused)) => { + JOBS.with(|jobs| jobs.borrow_mut().insert(key.0, job)); + self.script_key = Some(key); + None + } + Ok(Ok(Progress::Done(_))) => Some(self.script_commit(job)), + } + } + + fn script_failed(&mut self, job: Job, e: &RunError) -> Result { + let report = failure_report(&job.name, e, "", &job.host, job.realm.fuel_left()); + drop(job); + raise_ids(self); + self.script_stop.clear(); + self.reset_tool(); + cmd::compositefonts::sync(self); + let message = failure_text(&report); + self.script_report = Some(report); + Err(EngineError::Other(message)) + } + + /// Makes the working copy the session's state: one undo step for each document whose art + /// changed, nothing for the others. + fn script_commit(&mut self, mut job: Job) -> Result { + // The working copy goes into the session; `job.world` holds the state before the run. + job.world.swap(self); + self.prefs = merged_prefs(&job.world.start_prefs, &self.prefs, &job.world.choices.prefs); + // The Caps Lock state takes the run's value only when the run changed it. + if self.caps_lock == job.world.start_caps_lock { + self.caps_lock = job.world.choices.caps_lock; + } + note_ids(self); + raise_ids(self); + let mut start = std::mem::take(&mut job.world.docs); + for st in &self.docs { + let changed = start.iter().find(|b| b.uid == st.uid).is_none_or(|b| !st.same_content(&b.doc)); + if changed && (!crate::sanity::doc_sane(&st.doc, &st.selection) || st.doc.too_deep(None)) { + job.world.docs = start; + job.world.swap(self); + let e = RunError { kind: RunErrorKind::Internal, message: INVALID_RESULT.to_string(), line: 0, column: 0 }; + return self.script_failed(job, &e); + } + } + let mut changed_names = Vec::new(); + for st in &mut self.docs { + let Some(b) = start.iter_mut().find(|b| b.uid == st.uid) else { + // A document the script opened or made starts with no undo steps. + st.history = crate::History { limit: st.history.limit, ..crate::History::default() }; + st.revision += 1; + changed_names.push(st.title()); + continue; + }; + let changed = !st.same_content(&b.doc); + st.history = std::mem::take(&mut b.history); + st.recovery.clone_from(&b.recovery); + if changed { + st.push_undo(STEP_LABEL.to_string(), b.doc.clone(), Arc::new(b.selection.clone())); + changed_names.push(st.title()); + } + if changed || st.revision != b.revision { + st.revision = st.revision.max(b.revision) + 1; + } + st.sync_new_art(); + } + // A document a frontend opened while the run went on stays open. + for st in start.iter().filter(|b| !job.start_uids.contains(&b.uid)) { + self.docs.push(st.clone()); + } + // A document the script closed is gone now, with its recovery copy. + for b in start.iter().filter(|b| job.start_uids.contains(&b.uid) && !self.docs.iter().any(|d| d.uid == b.uid)) { + cmd::recovery::forget_closed(self, b); + } + // A document the script saved has nothing left to recover. + cmd::recovery::forget_clean(self); + let entries: Vec<_> = self.journal.iter().cloned().collect(); + self.journal = std::mem::take(&mut job.world.journal); + for (id, p) in entries { + self.journal.push((id, p)); + } + self.script_stop.clear(); + self.reset_tool(); + cmd::compositefonts::sync(self); + let host = &job.host; + let report = json!({ + "ok": true, + "name": job.name, + "changed": changed_names, + "written": *host.written.borrow(), + "log": *host.log.borrow(), + "fuelUsed": job.realm.limits().fuel - job.realm.fuel_left(), + "hostCalls": host.calls.get(), + }); + self.script_report = Some(report.clone()); + Ok(report) + } + + /// Runs the running script until it ends. + pub(crate) fn script_run_to_end(&mut self) -> Result { + loop { + if let Some(result) = self.script_pump() { + return result; + } + if self.script_waiting() { + self.script_stop.set(); + } + } + } +} + +const OPEN_EDIT: &str = "a drag or an undo group is open; finish it before running a script"; +const INVALID_RESULT: &str = "the script left a document that cannot be kept"; +const JOB_GONE: &str = "the script's run is no longer available"; +const HISTORY_LOST: &str = "a failed command changed undo steps that could not be put back, so the script was stopped"; +// Text a script reads from the errors it catches, or that ends its run with its name and place. +const OVER_CALLS: &str = "the script made more host calls than one run may make"; +const OVER_BRIDGE: &str = "the script passed more data to and from commands than one run may pass"; +const OVER_GROWTH: &str = "the script added more objects and data to the documents than one run may add"; +const NO_COMMAND_ID: &str = "vc.run: give a command id, as a string"; +const TOO_MANY_ARGUMENTS: &str = "vc.run: takes a command id and an object of parameters"; +const PARAMS_NOT_OBJECT: &str = "vc.run: the parameters must be an object"; +const LOG_FULL: &str = "vc.log: the log of this run is full"; +const NO_RECOVERY_COPY: &str = "a recovery copy could not be written, so the script was not run"; + +/// The report of a run that failed. +fn failure_report(name: &str, e: &RunError, source: &str, host: &Host, fuel_left: u64) -> Value { + json!({ + "ok": false, + "kind": kind_id(&e.kind), + "message": explained(&e.kind, &e.message, source, e.line), + "name": name, + "line": e.line, + "column": e.column, + "written": *host.written.borrow(), + "log": *host.log.borrow(), + "fuelLeft": fuel_left, + }) +} + +/// The text of a failed run's error. +fn failure_text(report: &Value) -> String { + let s = |k: &str| report[k].as_str().unwrap_or_default(); + let (line, column) = (report["line"].as_u64().unwrap_or(0), report["column"].as_u64().unwrap_or(0)); + let at = if line > 0 { format!(" line {line}, column {column}") } else { String::new() }; + let written = report["written"].as_array().map_or(0, Vec::len); + let kept = if written > 0 { + let paths: Vec<&str> = report["written"].as_array().into_iter().flatten().filter_map(Value::as_str).collect(); + format!(" (these files stay written: {})", paths.join(", ")) + } else { + String::new() + }; + format!("{}:{at}: {} ({}){kept}", s("name"), s("message"), s("kind")) +} + +/// A run's slice: the working copy in, the real session lent to the host functions, one measured +/// slice run, and everything back. A panic in the interpreter is the outer `Err`. +fn run_slice(s: &mut Session, job: &mut Job) -> std::result::Result, String> { + let depth = std::mem::replace(&mut s.depth, 0); + job.world.swap(s); + s.script_in_run = true; + let cell = job.host.session.clone(); + std::mem::swap(s, &mut *cell.borrow_mut()); + let realm = &mut job.realm; + let r = guard::catch_panic(|| { + #[cfg(test)] + if PANIC_IN_SLICE.with(Cell::get) { + panic!("a slice failed"); + } + realm.advance(SLICE_FUEL) + }); + std::mem::swap(s, &mut *cell.borrow_mut()); + s.script_in_run = false; + job.world.swap(s); + s.depth = depth; + r +} + +/// The objects a run may add before it is asked to continue or stop. +fn growth_objects() -> u64 { + #[cfg(test)] + if let Some(n) = TEST_GROWTH.with(Cell::get) { + return n; + } + GROWTH_OBJECTS +} + +/// The limits of a command's result on its way to the script. +fn result_limits() -> DataLimits { + #[cfg(test)] + if let Some(bytes) = TEST_RESULT_BYTES.with(Cell::get) { + return DataLimits { bytes, ..DataLimits::default() }; + } + DataLimits::default() +} + +#[cfg(test)] +thread_local! { + /// Tests: the bytes a command's result may hold on its way to the script. + pub(crate) static TEST_RESULT_BYTES: Cell> = const { Cell::new(None) }; + /// Tests: makes the next slice panic. + pub(crate) static PANIC_IN_SLICE: Cell = const { Cell::new(false) }; + /// Tests: the objects a run may add in place of [`GROWTH_OBJECTS`]. + pub(crate) static TEST_GROWTH: Cell> = const { Cell::new(None) }; +} diff --git a/crates/engine/src/session/documents.rs b/crates/engine/src/session/documents.rs index 208088a4cd..8a1ef8f69b 100644 --- a/crates/engine/src/session/documents.rs +++ b/crates/engine/src/session/documents.rs @@ -129,6 +129,13 @@ impl Session { link_scan: None, global_edit_options: Default::default(), keyboard_text: false, + script_key: None, + script_stop: vectorcraft_js::Interrupt::new(), + script_report: None, + script_frames: false, + script_high_water: Default::default(), + script_in_run: false, + script_copy_first: cfg!(target_arch = "wasm32"), } } diff --git a/crates/engine/src/session/edit.rs b/crates/engine/src/session/edit.rs index 7c72da22db..1020e11a51 100644 --- a/crates/engine/src/session/edit.rs +++ b/crates/engine/src/session/edit.rs @@ -7,6 +7,9 @@ impl Session { /// Run `f` on a mutable copy of the active document. Outside an interaction this records one /// undo step labelled `label`; inside one it just mutates (the interaction commits later). pub fn edit(&mut self, label: &str, f: impl FnOnce(&mut Document, &mut Selection) -> Result) -> Result { + if self.script_running() { + return Err(EngineError::Busy); + } // An edit made while typing (the Transform panel) is a step of its own: inside the typing // session, the next keystroke's preview would start again from before it (#1881). if !self.previewing && cmd::typing_in_progress(self) { @@ -225,6 +228,9 @@ impl Session { } pub fn begin_interaction(&mut self, label: &str) -> Result<()> { + if self.script_running() { + return Err(EngineError::Busy); + } // Typing in progress is kept first: a drag or a dialog's preview would otherwise start // from the snapshot taken before the typing, and drop it (#1881). if label != "Typing" && cmd::typing_in_progress(self) { @@ -262,6 +268,9 @@ impl Session { /// Re-apply `cmd` on top of the interaction snapshot (replacing the previous preview). pub fn preview(&mut self, cmd: &str, params: &Value) -> Result { + if self.script_running() { + return Err(EngineError::Busy); + } let (paint, restore_paint) = { let menu = self.menu.clone(); let st = self.doc_mut()?; diff --git a/crates/engine/src/session/execute.rs b/crates/engine/src/session/execute.rs index 81c839068e..7dd5d8ae64 100644 --- a/crates/engine/src/session/execute.rs +++ b/crates/engine/src/session/execute.rs @@ -39,6 +39,14 @@ impl Session { /// Execute a command by id. This is THE entry point for every frontend. 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")) { + return Err(EngineError::Busy); + } + // A step of a batch a script runs is held to the same rule as the script's own commands. + if self.script_in_run && crate::script::refused_to_scripts(id) { + return Err(EngineError::Other(crate::script::refused_text(id))); + } // An edit the active tool is computing on another thread (a Shape Builder merge) is // applied before a command that may edit, select, save or give a document a new revision, // as the click came first. Queries that only read do not wait for it. @@ -302,8 +310,13 @@ impl Session { /// document goes back to how it was before the command (its art, selection, interaction and /// undo history), and the same document stays active, instead of crashing the frontend. pub(crate) fn run_guarded(&mut self, id: &str, f: impl FnOnce(&mut Self) -> Result) -> Result { - let snapshot: Vec<_> = - self.docs.iter().map(|d| (d.uid, d.doc.clone(), d.selection.clone(), d.interaction.clone(), d.history.clone())).collect(); + // In a script's run a panic ends the run, and the run's rollback puts the histories back. + let in_run = self.script_in_run; + let snapshot: Vec<_> = self + .docs + .iter() + .map(|d| (d.uid, d.doc.clone(), d.selection.clone(), d.interaction.clone(), (!in_run).then(|| d.history.clone()))) + .collect(); let active = self.active().map(|d| d.uid); let r = match guard::catch_panic(|| self.run_nested(f)) { Ok(r) => r, @@ -316,7 +329,9 @@ impl Session { st.doc = doc; st.selection = selection; st.interaction = interaction; - st.history = history; + if let Some(history) = history { + st.history = history; + } cmd::globaledit::follow_history(st); st.drop_stale_variables_highlight(); st.revision += 1; diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 6063feab45..f6e32d719e 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -149,6 +149,7 @@ mod repeat_edit; mod save; mod saveoptions; mod scalestrokes; +mod script_run; mod scripts; mod select_ids_first; mod shaper; diff --git a/crates/engine/src/tests/linkwatch.rs b/crates/engine/src/tests/linkwatch.rs index 37aac5df5c..7fc8f0a4ba 100644 --- a/crates/engine/src/tests/linkwatch.rs +++ b/crates/engine/src/tests/linkwatch.rs @@ -147,6 +147,26 @@ fn a_look_that_stores_its_stamps_between_the_polls_reads_keeps_them() { assert!(s.link_scan.is_none()); } +#[test] +fn a_change_during_a_script_waits_for_the_script_to_end() { + let dir = Folder::new("watch-script"); + let path = dir.file("art.png"); + std::fs::write(&path, png(40, 40, RED)).unwrap(); + let mut s = session(); + s.prefs.update_links = "automatically".into(); + let id = place(&mut s, &path); + look(&mut s); + save(&path, &png(40, 40, BLUE)); + s.start_link_scan(); + s.wait_link_scan(); + s.script_frames = true; + s.execute("script.run", &json!({"source": "while (true) {}"})).unwrap(); + assert!(s.poll_link_scan().is_none(), "the finished look waits"); + assert!(s.script_abandon()); + assert_eq!(s.poll_link_scan().expect("the stamps are applied").unwrap()["updated"], json!([id.0])); + assert_eq!(colour(&s), BLUE); +} + #[test] fn a_change_during_a_drag_waits_for_the_drag_to_end() { let dir = Folder::new("watch-drag"); diff --git a/crates/engine/src/tests/script_run.rs b/crates/engine/src/tests/script_run.rs new file mode 100644 index 0000000000..5480ba499d --- /dev/null +++ b/crates/engine/src/tests/script_run.rs @@ -0,0 +1,999 @@ +//! `script.run` and `script.stop`: one transaction per run, the rollback after a throw, a limit, a +//! stop or a panic, the mutation lease between slices, ids, growth and what a run reports. + +use std::cell::Cell; + +use serde_json::{Value, json}; + +use crate::script::{PANIC_IN_SLICE, TEST_GROWTH, TEST_RESULT_BYTES}; +use crate::*; + +fn rect(x: i64) -> Value { + json!({"x": x, "y": 0, "width": 10, "height": 10}) +} + +/// Two open documents, each with one rectangle, the second one active. +fn two_docs() -> Session { + let mut s = Session::new(); + for x in [0, 50] { + s.execute("file.new", &json!({})).unwrap(); + s.execute("shape.rectangle", &rect(x)).unwrap(); + } + s +} + +/// What a rollback has to put back. +fn state(s: &Session) -> Value { + let docs: Vec = s + .documents() + .iter() + .map(|d| { + json!({ + "uid": d.uid, + "art": format!("{:?}", d.doc.layers), + "selection": d.selection.objects.iter().map(|i| i.0).collect::>(), + "undo": d.history.undo.iter().map(|e| e.label.clone()).collect::>(), + "redo": d.history.redo.len(), + "path": d.path, + "dirty": d.is_dirty(), + }) + }) + .collect(); + json!({"docs": docs, "active": s.active().map(|d| d.uid), "journal": s.journal.len(), "paint": format!("{:?}", s.paint)}) +} + +fn run(s: &mut Session, source: &str) -> Result { + s.execute("script.run", &json!({"source": source, "name": "t.js"})) +} + +fn objects(s: &Session, doc: usize) -> usize { + s.documents()[doc].doc.layers.iter().map(|l| l.children().map_or(0, Vec::len)).sum() +} + +/// A framed run of `source`, one slice in. +fn paused(s: &mut Session, source: &str) { + s.script_frames = true; + assert_eq!(run(s, source).unwrap()["running"], true); + assert!(s.script_pump().is_none()); + assert!(s.script_running()); +} + +fn two_rect_script() -> String { + "vc.run('shape.rectangle', {x:100,y:0,width:5,height:5});\ + vc.run('shape.rectangle', {x:110,y:0,width:5,height:5});\ + vc.run('document.activate', {index:0});\ + vc.run('shape.rectangle', {x:120,y:0,width:5,height:5});\ + vc.run('document.activate', {index:1});" + .to_string() +} + +#[test] +fn a_run_is_one_undo_step_in_each_document_it_changed() { + let mut s = two_docs(); + let before = state(&s); + let r = run(&mut s, &two_rect_script()).unwrap(); + assert_eq!(r["ok"], true); + assert_eq!((objects(&s, 0), objects(&s, 1)), (2, 3)); + assert_eq!(s.documents()[0].history.undo.last().unwrap().label, "Run Script"); + assert_eq!(s.documents()[1].history.undo.last().unwrap().label, "Run Script"); + assert_eq!(s.documents()[1].history.undo.len(), before["docs"][1]["undo"].as_array().unwrap().len() + 1); + let after = format!("{:?}", s.documents()[1].doc.layers); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(objects(&s, 1), 1); + assert_eq!(format!("{:?}", s.documents()[1].doc.layers), before["docs"][1]["art"].as_str().unwrap()); + assert_eq!(s.documents()[1].selection.objects.len(), before["docs"][1]["selection"].as_array().unwrap().len()); + s.execute("edit.redo", &json!({})).unwrap(); + assert_eq!(format!("{:?}", s.documents()[1].doc.layers), after); +} + +#[test] +fn a_run_that_changes_nothing_leaves_no_step_no_mark_and_no_journal_entry() { + for source in ["", "var a = 1 + 2;", "vc.log(vc.document); vc.commands.length;"] { + let mut s = two_docs(); + s.execute("document.save", &json!({"path": std::env::temp_dir().join(format!("vc-noop-{}.svg", std::process::id())).to_string_lossy()})) + .unwrap(); + let before = state(&s); + let revisions = |s: &Session| s.documents().iter().map(|d| d.revision).collect::>(); + let revisions_before = revisions(&s); + let r = run(&mut s, source).unwrap(); + assert_eq!(r["changed"], json!([]), "{source}"); + assert_eq!(state(&s), before, "{source}"); + assert_eq!(revisions(&s), revisions_before, "{source}"); + } +} + +#[test] +fn a_caught_command_failure_leaves_nothing_behind_and_the_script_goes_on() { + let mut s = two_docs(); + let source = "var m = '';\ + try { vc.run('command.batch', {commands: [\ + {command:'shape.rectangle', params:{x:1,y:1,width:1,height:1}},\ + {command:'no.such', params:{}}]}); } catch (e) { m = e.message; }\ + try { vc.run('shape.rectangle', {x:'bad'}); } catch (e) { m += '|' + e.name; }\ + vc.log(m); vc.run('shape.rectangle', {x:200,y:0,width:5,height:5});"; + let r = run(&mut s, source).unwrap(); + assert_eq!(objects(&s, 1), 2, "{r}"); + assert!(r["log"][0].as_str().unwrap().contains("|Error"), "{r}"); +} + +#[test] +fn a_failure_puts_back_every_document_and_the_session() { + enum How { + Throw, + Fuel, + Stop, + Panic, + } + for how in [How::Throw, How::Fuel, How::Stop, How::Panic] { + let mut s = two_docs(); + let before = state(&s); + let edits = two_rect_script(); + let r = match how { + How::Throw => run(&mut s, &format!("{edits} throw new Error('boom');")), + How::Fuel => s.execute("script.run", &json!({"source": format!("{edits} while (true) {{}}"), "maxFuel": 2_000_000})), + How::Stop => { + paused(&mut s, &format!("{edits} while (true) {{}}")); + assert_eq!(s.execute("script.stop", &json!({})).unwrap()["stopped"], true); + assert_eq!(s.execute("script.stop", &json!({})).unwrap()["stopped"], true); + s.script_pump().unwrap() + } + How::Panic => { + paused(&mut s, &format!("{edits} while (true) {{}}")); + PANIC_IN_SLICE.with(|p| p.set(true)); + let r = s.script_pump().unwrap(); + PANIC_IN_SLICE.with(|p| p.set(false)); + r + } + }; + assert!(r.is_err()); + assert_eq!(state(&s), before); + assert!(!s.script_running()); + s.script_frames = false; + assert_eq!(run(&mut s, "1").unwrap()["ok"], true, "a later run starts"); + } +} + +#[test] +fn a_stop_with_no_run_reports_it() { + assert_eq!(Session::new().execute("script.stop", &json!({})).unwrap()["stopped"], false); +} + +#[test] +fn an_error_names_the_script_its_place_and_kind() { + let mut s = two_docs(); + let e = run(&mut s, "var a;\n throw new TypeError('no');").unwrap_err().to_string(); + assert_eq!(e, "t.js: line 2, column 3: TypeError: no (thrown)"); + let e = run(&mut s, "var = 1;").unwrap_err().to_string(); + assert!(e.starts_with("t.js: line 1,") && e.ends_with("(syntax)"), "{e}"); + assert!(run(&mut s, "app.activeDocument;").unwrap_err().to_string().contains("`vc`")); + assert!(run(&mut s, "#target x\n1").unwrap_err().to_string().contains("#target")); + assert_eq!(s.script_report().unwrap()["line"], 1); +} + +#[test] +fn bad_parameters_are_refused_before_anything_runs() { + let mut s = two_docs(); + let before = state(&s); + let mut deep = json!(1); + for _ in 0..100 { + deep = json!([deep]); + } + for p in [ + json!({}), + json!({"source": "1", "args": {"a": deep}}), + json!({"path": "a", "source": "b"}), + json!({"path": ""}), + json!({"path": 1}), + json!({"source": "1", "nope": 1}), + json!({"source": "1", "args": []}), + json!({"source": "1", "args": {"a": "x".repeat(1 << 20)}}), + json!({"source": "1", "answers": {"a": 1}}), + json!({"source": "1", "answers": 1}), + json!({"source": "1", "maxFuel": 0}), + json!({"source": "1", "maxFuel": -1}), + json!({"source": "1", "maxFuel": 1.5}), + json!({"source": "1", "maxFuel": "9"}), + json!({"source": "1", "maxFuel": 100_000_000_001u64}), + ] { + assert!(matches!(s.execute("script.run", &p), Err(EngineError::BadParams { .. })), "{p}"); + } + assert_eq!(state(&s), before); +} + +#[test] +fn files_are_checked_before_they_are_read() { + let dir = std::env::temp_dir().join(format!("vc-script-run-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + let write = |name: &str, bytes: &[u8]| { + let p = dir.join(name); + std::fs::write(&p, bytes).unwrap(); + p.to_string_lossy().into_owned() + }; + let mut s = two_docs(); + let path = |p: &str| json!({"path": p}); + let ok = write("Bézier (1) & co.js", b"\xef\xbb\xbfvc.log(1);\r\nvc.log(2);\r\n"); + let r = s.execute("script.run", &path(&ok)).unwrap(); + assert_eq!((r["log"].clone(), r["name"].as_str()), (json!([1, 2]), Some("Bézier (1) & co.js"))); + let invalid = write("a.js", b"var a = '\xff';"); + assert!(s.execute("script.run", &path(&invalid)).unwrap_err().to_string().contains("UTF-8")); + let huge = write("huge.js", &vec![b' '; script::MAX_SOURCE_BYTES + 1]); + assert!(s.execute("script.run", &path(&huge)).unwrap_err().to_string().contains("too large")); + let compiled = write("b.jsxbin", b"@JSXBIN@ES@2.0@"); + assert!(s.execute("script.run", &path(&compiled)).unwrap_err().to_string().contains("compiled")); + let renamed = write("c.js", b"@JSXBIN@ES@2.0@"); + assert!(s.execute("script.run", &path(&renamed)).unwrap_err().to_string().contains("compiled")); + assert!(s.execute("script.run", &path(&dir.to_string_lossy())).is_err()); + let huge_source = " ".repeat(script::MAX_SOURCE_BYTES + 1); + assert!(run(&mut s, &huge_source).unwrap_err().to_string().contains("too large")); + let other = write("notes.txt", b"vc.log(1);"); + assert!(matches!(s.execute("script.run", &path(&other)), Err(EngineError::BadParams { .. })), "a text file that is not a script"); + let upper = write("UP.JSX", b"vc.log(3);"); + assert_eq!(s.execute("script.run", &path(&upper)).unwrap()["log"], json!([3])); + std::fs::create_dir_all(dir.join("folder.js")).unwrap(); + assert!(s.execute("script.run", &path(&dir.join("folder.js").to_string_lossy())).is_err()); + let _ = std::fs::remove_dir_all(&dir); +} + +#[test] +fn a_failed_batch_puts_back_the_session_and_names_a_file_it_wrote() { + let path = std::env::temp_dir().join(format!("vc-script-batch-{}.svg", std::process::id())); + let _ = std::fs::remove_file(&path); + let p = path.to_string_lossy().into_owned(); + let mut s = two_docs(); + let source = format!( + "try {{ vc.run('command.batch', {{commands: [\ + {{command: 'view.guides.lock', params: {{locked: true}}}},\ + {{command: 'document.export', params: {{path: {p:?}, format: 'svg'}}}},\ + {{command: 'no.such', params: {{}}}}]}}); }} catch (e) {{ vc.log(e.name); }}" + ); + let r = run(&mut s, &source).unwrap(); + assert_eq!(r["log"], json!(["Error"]), "{r}"); + assert!(!s.guides_locked(), "the failed batch's Lock Guides does not stay"); + assert!(path.exists()); + assert_eq!(r["written"], json!([p]), "{r}"); + let _ = std::fs::remove_file(&path); +} + +#[test] +fn an_export_that_fails_names_no_file() { + let path = std::env::temp_dir().join(format!("vc-script-no-folder-{}", std::process::id())).join("out.svg"); + let p = path.to_string_lossy().into_owned(); + let mut s = two_docs(); + let source = format!("try {{ vc.run('document.export', {{path: {p:?}, format: 'svg'}}); }} catch (e) {{ vc.log(e.name); }}"); + let r = run(&mut s, &source).unwrap(); + assert_eq!(r["log"], json!(["Error"]), "{r}"); + assert!(!path.exists()); + assert_eq!(r["written"], json!([]), "{r}"); +} + +#[test] +fn a_failed_run_puts_back_the_choices_its_commands_made() { + let mut s = two_docs(); + let before = s.global_edit_options.clone(); + let source = "vc.run('select.globalEditOptions', {appearance: !vc.run('select.globalEditOptions', {}).appearance}); throw new Error('x');"; + assert!(run(&mut s, source).is_err()); + assert_eq!(s.global_edit_options, before); + let source = "try { vc.run('command.batch', {commands: [\ + {command: 'select.globalEditOptions', params: {size: true}},\ + {command: 'no.such', params: {}}]}); } catch (e) {}"; + run(&mut s, source).unwrap(); + assert_eq!(s.global_edit_options, before, "the failed command's choice went back"); + + assert!(!s.caps_lock); + assert!(run(&mut s, "vc.run('view.capsLock', {on: true}); throw new Error('x');").is_err()); + assert!(!s.caps_lock, "the Caps Lock state went back"); + run(&mut s, "vc.run('view.capsLock', {on: true});").unwrap(); + assert!(s.caps_lock, "a finished run keeps it"); +} + +#[test] +fn a_failed_run_puts_back_the_preferences_its_commands_changed() { + let mut s = two_docs(); + let basic = s.prefs.new_art_basic; + assert!(run(&mut s, &format!("vc.run('appearance.setNewArtBasic', {{on: {}}}); throw new Error('x');", !basic)).is_err()); + assert_eq!(s.prefs.new_art_basic, basic); +} + +#[test] +fn a_finished_run_keeps_its_preferences_and_the_ones_the_app_changed_meanwhile() { + let mut s = two_docs(); + let (basic, increment) = (s.prefs.new_art_basic, s.prefs.keyboard_increment); + paused(&mut s, &format!("vc.run('appearance.setNewArtBasic', {{on: {}}}); for (var i = 0; i < 2000000; i++) {{}}", !basic)); + assert_eq!(s.prefs.new_art_basic, basic, "between slices the app sees the preferences before the run"); + s.prefs.keyboard_increment = increment + 1.0; + s.execute("view.capsLock", &json!({"on": true})).unwrap(); + while s.script_pump().is_none() {} + assert_eq!((s.prefs.new_art_basic, s.prefs.keyboard_increment), (!basic, increment + 1.0)); + assert!(s.caps_lock, "the Caps Lock state the app reported during the run stays"); +} + +#[test] +fn a_script_cannot_load_the_place_cursor() { + let mut s = two_docs(); + let e = run(&mut s, "vc.run('file.place.queue', {paths: []});").unwrap_err().to_string(); + assert!(e.contains("a script cannot run `file.place.queue`"), "{e}"); + let listed = run(&mut s, "vc.log(vc.commands.some(function (c) { return c.id === 'file.place.queue'; }));").unwrap(); + assert_eq!(listed["log"], json!([false]), "{listed}"); +} + +#[test] +fn a_command_whose_result_cannot_cross_is_put_back() { + TEST_RESULT_BYTES.with(|b| b.set(Some(1))); + let mut s = two_docs(); + let r = run(&mut s, "try { vc.run('shape.rectangle', {x:1,y:1,width:1,height:1}); } catch (e) { vc.log(e.name); }"); + TEST_RESULT_BYTES.with(|b| b.set(None)); + let r = r.unwrap(); + assert_eq!(r["log"], json!(["RangeError"]), "{r}"); + assert_eq!(r["changed"], json!([]), "{r}"); + assert_eq!((objects(&s, 0), objects(&s, 1)), (1, 1)); +} + +#[test] +fn an_abandoned_run_reports_the_files_it_wrote() { + let path = std::env::temp_dir().join(format!("vc-script-abandon-{}.svg", std::process::id())); + let _ = std::fs::remove_file(&path); + let p = path.to_string_lossy().into_owned(); + let mut s = two_docs(); + paused(&mut s, &format!("vc.run('document.export', {{path: {p:?}, format: 'svg'}}); while (true) {{}}")); + assert!(path.exists(), "the first slice exported"); + assert!(s.script_abandon()); + let report = s.script_report().unwrap(); + assert_eq!((report["kind"].as_str(), report["written"].clone()), (Some("stopped"), json!([p])), "{report}"); + assert!(s.script_failure_text().unwrap().contains(&p)); + let _ = std::fs::remove_file(&path); +} + +#[test] +fn a_run_that_only_closes_a_document_keeps_its_journal_entry() { + let mut s = two_docs(); + let journal = s.journal.len(); + let r = run(&mut s, "vc.run('file.close', {index: 1});").unwrap(); + assert_eq!(r["changed"], json!([]), "{r}"); + assert_eq!(s.documents().len(), 1); + assert_eq!(s.journal.len(), journal + 1); + assert_eq!(s.journal.iter().last().unwrap().0, "file.close"); +} + +#[test] +fn a_command_that_can_fail_after_copying_has_the_clipboard_put_back() { + let mut s = two_docs(); + let keep_clipboard = |s: &mut Session, id: &str| { + let save = script::Savepoint::take(s, id); + s.clipboard.source_artboard = Some(Default::default()); + save.restore(s); + }; + keep_clipboard(&mut s, "edit.cut"); + assert_eq!(s.clipboard.source_artboard, None, "put back"); + s.clipboard.source_artboard = Some(Default::default()); + keep_clipboard(&mut s, "shape.rectangle"); + assert!(s.clipboard.source_artboard.is_some(), "only those commands pay for a copy of the clipboard"); +} + +#[test] +fn a_commands_savepoint_copies_the_same_number_of_undo_steps_however_long_the_runs_history() { + let copied = |n: usize| { + let mut s = two_docs(); + crate::history::ENTRY_CLONES.with(|c| c.set(0)); + let r = run(&mut s, &format!("for (var i = 0; i < {n}; i++) vc.run('shape.rectangle', {{x:i,y:1,width:1,height:1}});")).unwrap(); + assert_eq!(r["ok"], true); + assert_eq!(objects(&s, 1), n + 1); + crate::history::ENTRY_CLONES.with(Cell::get) + }; + let (few, many) = (copied(20), copied(200)); + // Each command copies at most its document's newest step, whatever the history holds. + assert!(many <= 200 + few, "{few} steps copied for 20 commands, {many} for 200"); +} + +#[test] +fn undo_redo_and_a_long_redo_stack_copy_the_same_number_of_steps_per_command() { + let copied = |n: usize| { + let mut s = two_docs(); + crate::history::ENTRY_CLONES.with(|c| c.set(0)); + let source = format!( + "for (var i = 0; i < {n}; i++) vc.run('shape.rectangle', {{x:i,y:1,width:1,height:1}});\ + for (var i = 0; i < {n}; i++) vc.run('edit.undo');\ + for (var i = 0; i < {n}; i++) vc.run('select.none');\ + for (var i = 0; i < {n}; i++) vc.run('edit.redo');" + ); + let r = run(&mut s, &source).unwrap(); + assert_eq!(r["ok"], true, "{r}"); + assert_eq!(objects(&s, 1), n + 1); + crate::history::ENTRY_CLONES.with(Cell::get) + }; + let (few, many) = (copied(20), copied(200)); + // Ten times the commands copy about ten times the steps: each command copies its document's + // newest undo and redo steps, whatever the stacks hold. + assert!(many <= 12 * few, "{few} steps copied for 80 commands, {many} for 800"); +} + +#[test] +fn a_failed_command_gives_back_the_redo_steps_and_an_undo_it_made() { + let mut s = two_docs(); + for x in 1..=3 { + s.execute("shape.rectangle", &rect(x)).unwrap(); + } + for _ in 0..2 { + s.execute("edit.undo", &json!({})).unwrap(); + } + let before = state(&s); + let save = script::Savepoint::take(&mut s, "shape.rectangle"); + s.execute("shape.rectangle", &rect(9)).unwrap(); + assert_eq!(s.documents()[1].history.redo.len(), 0); + assert!(save.restore(&mut s), "the redo steps the new step cleared are put back"); + assert_eq!(state(&s), before); + let save = script::Savepoint::take(&mut s, "edit.undo"); + s.execute("edit.undo", &json!({})).unwrap(); + s.execute("edit.redo", &json!({})).unwrap(); + s.execute("edit.redo", &json!({})).unwrap(); + assert!(save.restore(&mut s)); + assert_eq!(state(&s), before); + for _ in 0..2 { + s.execute("edit.redo", &json!({})).unwrap(); + } + assert_eq!(objects(&s, 1), 4); +} + +#[test] +fn a_failed_command_at_the_history_limit_keeps_the_oldest_step() { + let mut s = two_docs(); + s.docs[1].history.limit = 5; + let before = state(&s); + for x in 1..=5 { + s.execute("shape.rectangle", &rect(x)).unwrap(); + } + let save = script::Savepoint::take(&mut s, "shape.rectangle"); + s.execute("shape.rectangle", &rect(9)).unwrap(); + assert!(save.restore(&mut s), "the step the limit would have let go is put back"); + assert_eq!(objects(&s, 1), 6); + for _ in 0..5 { + s.execute("edit.undo", &json!({})).unwrap(); + } + assert_eq!(state(&s)["docs"][1]["art"], before["docs"][1]["art"]); +} + +#[test] +fn a_snapshot_too_large_to_cross_throws_instead_of_reading_as_no_document() { + let mut s = two_docs(); + s.docs[1].path = Some("x".repeat(17 << 20)); + let r = run(&mut s, "var m = ''; try { vc.document; m = 'read'; } catch (e) { m = e.name + ': ' + e.message; } vc.log(m);").unwrap(); + let m = r["log"][0].as_str().unwrap(); + assert!(m.starts_with("RangeError: vc.document.") && m.ends_with("is too large for a script"), "{m}"); +} + +#[test] +fn recovery_copies_made_between_slices_hold_the_art_before_the_run() { + let store = std::sync::Arc::new(cmd::recovery::MemoryStore::default()); + let mut s = two_docs(); + s.recovery.set_store(store.clone()); + paused(&mut s, &format!("{} while (true) {{}}", two_rect_script())); + cmd::recovery::save_copies(&mut s).unwrap(); + s.script_abandon(); + drop(s); + let mut s = Session::new(); + s.recovery.set_store(store); + let r = s.execute("file.recovery.restore", &json!({})).unwrap(); + assert_eq!(r["restored"].as_array().map(Vec::len), Some(2), "{r}"); + assert_eq!((objects(&s, 0), objects(&s, 1)), (1, 1), "the copies hold the art from before the run"); +} + +#[test] +fn values_that_cannot_cross_are_named_and_shared_ones_can() { + let mut s = two_docs(); + let cases = [ + ("var a = {}; a.a = a; vc.run('shape.rectangle', a);", "RangeError|TypeError"), + ("var a = {}, c = a; for (var i = 0; i < 100; i++) { c.n = {}; c = c.n; } vc.run('shape.rectangle', a);", "RangeError|TypeError"), + ("vc.run('shape.rectangle', {x: 1/0});", "RangeError|TypeError"), + ("vc.run('shape.rectangle', {x: function () {}});", "RangeError|TypeError"), + ("vc.run('shape.rectangle', 7);", "TypeError"), + ("vc.run(7);", "TypeError"), + ]; + for (source, kinds) in cases { + let e = run(&mut s, source).unwrap_err().to_string(); + assert!(kinds.split('|').any(|k| e.contains(k)), "{source}: {e}"); + } + let r = run(&mut s, "var p = {w: 5}; vc.log({a: p, b: p}); var l = ''; for (var i = 0; i < 20; i++) l += 'xxxxxxxxxx'; vc.log(l);").unwrap(); + assert_eq!(r["log"][0], json!({"a": {"w": 5}, "b": {"w": 5}})); + assert_eq!(r["log"][1].as_str().unwrap().len(), 200); +} + +#[test] +fn commands_outside_the_documents_are_refused_in_a_batch_too() { + let mut s = two_docs(); + for source in [ + "vc.run('prefs.set', {key: 'a', value: 1});", + "vc.run('script.run', {source: '1'});", + "vc.run('script.stop');", + "vc.run('edit.undoGroup.begin', {});", + "vc.run('view.proofColors', {on: true});", + "vc.run('view.proofSetup', {});", + "vc.run('view.overprintPreview', {on: true});", + "vc.run('view.separationsPreview', {});", + "vc.run('command.batch', {commands: [{command: 'prefs.reset', params: {}}]});", + ] { + let e = run(&mut s, source).unwrap_err().to_string(); + assert!(e.contains("cannot run"), "{source}: {e}"); + } + let r = run(&mut s, "var c = vc.commands; var n = 0; for (var i = 0; i < c.length; i++) if (c[i].id.indexOf('prefs.') === 0) n++; vc.log(n); vc.log(c.length > 100);").unwrap(); + assert_eq!(r["log"], json!([0, true])); +} + +#[test] +fn a_script_cannot_clear_the_undo_steps_from_before_its_run() { + let mut s = two_docs(); + let steps = s.documents()[1].history.undo.len(); + let source = "vc.run('shape.rectangle', {x:9,y:9,width:1,height:1});\ + var m = ''; try { vc.run('edit.clearHistory'); } catch (e) { m = e.message; } vc.log(m);"; + let r = run(&mut s, source).unwrap(); + assert_eq!(r["log"], json!(["a script cannot run `edit.clearHistory`"]), "{r}"); + assert_eq!(s.documents()[1].history.undo.len(), steps + 1); +} + +#[test] +fn the_vc_object_reads_the_active_document_and_cannot_be_changed() { + let mut s = two_docs(); + let r = s + .execute( + "script.run", + &json!({"name": "x", "args": {"n": 2}, "source": "vc.args.n = 9; vc.api.version = 'x'; vc.log(vc.args.n); vc.log(vc.api.version); vc.log(vc.api.has('run')); vc.log(vc.api.has('nope')); vc.log(vc.document.artboards); vc.log(typeof vc.document.path);"}), + ) + .unwrap(); + assert_eq!(r["log"], json!([2, "1.0", true, false, 1, "object"])); + let mut empty = Session::new(); + assert_eq!(run(&mut empty, "vc.log(vc.document === null);").unwrap()["log"], json!([true])); + assert!(run(&mut empty, "vc.run('shape.rectangle', {x:0,y:0,width:1,height:1});").unwrap_err().to_string().contains("Error")); +} + +#[test] +fn the_log_is_bounded_and_a_script_can_catch_that() { + let mut s = two_docs(); + let r = run( + &mut s, + "var n = 0; try { while (true) { vc.log(n); n++; } } catch (e) { vc.run('document.inspect', {}); throw new Error(e.name + ' at ' + n); }", + ); + let e = r.unwrap_err().to_string(); + assert!(e.contains(&format!("RangeError at {}", script::MAX_LOG_LINES)), "{e}"); +} + +#[test] +fn between_slices_every_change_is_refused_and_readers_see_the_committed_art() { + let mut s = two_docs(); + let before = state(&s); + paused(&mut s, &format!("{} while (true) {{}}", two_rect_script())); + assert_eq!(state(&s), before); + for (id, p) in [ + ("shape.rectangle", rect(1)), + ("clipboard.importSvg", json!({})), + ("clipboard.importImage", json!({})), + ("clipboard.importText", json!({})), + ("clipboard.importPdf", json!({})), + ("clipboard.importEmf", json!({})), + ("clipboard.importEps", json!({})), + ("edit.undo", json!({})), + ("file.new", json!({})), + ("file.close", json!({})), + ("file.revert", json!({})), + ("file.recovery.restore", json!({})), + ("action.batch", json!({})), + ("command.batch", json!({"commands": []})), + ("effect.apply", json!({})), + ("script.run", json!({"source": "1"})), + ] { + assert!(matches!(s.execute(id, &p), Err(EngineError::Busy)), "{id}"); + } + assert!(matches!(s.begin_interaction("x"), Err(EngineError::Busy))); + assert!(matches!(s.edit("x", |_, _| Ok(())), Err(EngineError::Busy))); + assert!(matches!(s.preview("shape.rectangle", &rect(1)), Err(EngineError::Busy))); + let press = tools::PointerEvent { + kind: tools::PointerKind::Down, + ..serde_json::from_value(json!({"kind": "move", "pos": {"x": 0.0, "y": 0.0}})).unwrap() + }; + assert!(matches!(s.pointer(&press, ViewInfo::default()), Err(EngineError::Busy))); + let inspected = s.execute("document.inspect", &json!({})).unwrap(); + assert_eq!(inspected["layers"][0]["children"].as_array().map(Vec::len), Some(1), "{inspected}"); + assert_eq!(state(&s), before, "the refused commands changed nothing"); + s.script_abandon(); + assert_eq!(state(&s), before); + assert!(s.execute("shape.rectangle", &rect(1)).unwrap()["id"].is_u64()); +} + +#[test] +fn a_document_closed_or_opened_in_a_run_follows_the_run() { + let closing = "vc.run('file.close', {index: 0}); vc.run('file.new', {}); vc.run('shape.rectangle', {x:1,y:1,width:1,height:1});"; + let mut s = two_docs(); + let before = state(&s); + assert!(run(&mut s, &format!("{closing} throw new Error('x');")).is_err()); + assert_eq!(state(&s), before); + let first = s.documents()[0].uid; + run(&mut s, closing).unwrap(); + assert_eq!(s.documents().len(), 2); + assert!(s.documents().iter().all(|d| d.uid != first)); + assert_eq!(s.documents()[1].history.undo.len(), 0, "a document the script made starts with no undo steps"); +} + +#[test] +fn undo_in_a_run_reaches_only_the_runs_own_steps_and_old_ids_stay_dead() { + let mut s = two_docs(); + let history = s.documents()[1].history.undo.len(); + let source = "var p = vc.run('shape.rectangle', {x:1,y:1,width:1,height:1}).id;\ + vc.run('edit.undo');\ + var q = vc.run('shape.rectangle', {x:2,y:2,width:1,height:1}).id;\ + var why = '';\ + try { vc.run('edit.clear', {ids: [p]}); } catch (e) { why = e.message; }\ + vc.run('edit.undo');\ + try { vc.run('edit.undo'); why += '|undid a step from before the run'; } catch (e) { why += '|stopped'; }\ + vc.log({same: p === q, why: why});\ + vc.run('shape.rectangle', {x:3,y:3,width:1,height:1});"; + let r = run(&mut s, source).unwrap(); + assert_eq!(r["log"][0]["same"], false, "{r}"); + let why = r["log"][0]["why"].as_str().unwrap(); + assert!(why.ends_with("|stopped") && why.len() > "|stopped".len(), "{why}"); + assert_eq!(objects(&s, 1), 2); + assert_eq!(s.documents()[1].history.undo.len(), history + 1); +} + +#[test] +fn a_string_over_the_crossing_limit_does_not_cross() { + let limits = vectorcraft_js::DataLimits { bytes: 20, ..vectorcraft_js::DataLimits::default() }; + assert!(script::to_data(&json!("four"), &limits, 0, &mut (0, 0)).is_ok()); + assert_eq!(script::to_data(&json!("fives"), &limits, 0, &mut (0, 0)), Err(String::new())); +} + +#[test] +fn a_result_too_large_to_cross_names_its_place() { + let limits = vectorcraft_js::DataLimits { bytes: 90, ..vectorcraft_js::DataLimits::default() }; + let v = json!({"a": [1, {"name": "x".repeat(40)}]}); + assert_eq!(script::to_data(&v, &limits, 0, &mut (0, 0)), Err(".a[1].name".to_string())); +} + +#[test] +fn ids_given_out_in_an_abandoned_run_are_not_given_out_again() { + let mut s = two_docs(); + let before = s.active().unwrap().doc.peek_next_id(); + paused(&mut s, &format!("{} while (true) {{}}", two_rect_script())); + assert!(s.script_abandon()); + assert!(s.active().unwrap().doc.peek_next_id() > before); +} + +#[test] +fn ids_given_out_in_a_failed_run_are_not_given_out_again() { + let mut s = two_docs(); + let e = + run(&mut s, "var p = vc.run('shape.rectangle', {x:1,y:1,width:1,height:1}).id; throw new Error('id=' + p + ';');").unwrap_err().to_string(); + let used: u64 = e.split("id=").nth(1).unwrap().split(';').next().unwrap().parse().unwrap(); + let dirty = s.documents()[1].is_dirty(); + let id = s.execute("shape.rectangle", &rect(3)).unwrap()["id"].as_u64().unwrap(); + assert!(id > used, "{id} after {used}"); + assert!(dirty); +} + +#[test] +fn a_rollback_keeps_the_history_after_an_undo_in_the_run() { + let mut s = two_docs(); + let before = state(&s); + let source = "vc.run('shape.rectangle', {x:1,y:1,width:1,height:1}); vc.run('edit.undo'); throw new Error('x');"; + assert!(run(&mut s, source).is_err()); + assert_eq!(state(&s), before); +} + +#[test] +fn a_batch_joins_the_runs_one_step() { + let mut s = two_docs(); + let undo = s.documents()[1].history.undo.len(); + let source = "vc.run('command.batch', {commands: [\ + {command:'shape.rectangle', params:{x:1,y:1,width:1,height:1}},\ + {command:'shape.rectangle', params:{x:2,y:2,width:1,height:1}}]});"; + run(&mut s, source).unwrap(); + assert_eq!(s.documents()[1].history.undo.len(), undo + 1); + assert_eq!(objects(&s, 1), 3); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(objects(&s, 1), 1); +} + +#[test] +fn a_run_with_nobody_to_ask_ends_at_its_growth_allowance() { + TEST_GROWTH.with(|g| g.set(Some(20))); + let mut s = two_docs(); + let before = state(&s); + let source = "try { while (true) vc.run('shape.rectangle', {x:1,y:1,width:1,height:1}); } catch (e) { vc.run('shape.rectangle', {x:2,y:1,width:1,height:1}); }"; + let e = run(&mut s, source).unwrap_err().to_string(); + TEST_GROWTH.with(|g| g.set(None)); + assert!(e.contains("objects and data"), "{e}"); + assert_eq!(state(&s), before); +} + +#[test] +fn a_document_a_run_opens_counts_toward_its_growth_allowance() { + TEST_GROWTH.with(|g| g.set(Some(20))); + let rects: String = (0..30).map(|i| format!(r#""#)).collect(); + let svg = format!(r#"{rects}"#); + let data = vectorcraft_format::base64_encode(svg.as_bytes()); + let mut s = two_docs(); + let before = state(&s); + let source = format!("try {{ vc.run('document.open', {{name: 'a.svg', dataBase64: '{data}'}}); }} catch (e) {{}}"); + let e = run(&mut s, &source).unwrap_err().to_string(); + assert!(e.contains("objects and data"), "{e}"); + assert_eq!(state(&s), before); + + // A document whose art is all in a symbol counts it too. + let mut maker = Session::new(); + maker.execute("file.new", &json!({})).unwrap(); + for x in 0..30 { + maker.execute("shape.rectangle", &rect(x)).unwrap(); + } + maker.execute("select.all", &json!({})).unwrap(); + let instance = maker.execute("symbol.new", &json!({"name": "Many"})).unwrap()["id"].as_u64().unwrap(); + maker.execute("edit.clear", &json!({"ids": [instance]})).unwrap(); + assert_eq!(objects(&maker, 0), 0); + let data = maker.execute("document.serialize", &json!({})).unwrap()["dataBase64"].as_str().unwrap().to_string(); + let source = format!("vc.run('document.open', {{name: 'b.vectorcraft', dataBase64: '{data}'}});"); + let e = run(&mut s, &source).unwrap_err().to_string(); + TEST_GROWTH.with(|g| g.set(None)); + assert!(e.contains("objects and data"), "{e}"); + assert_eq!(state(&s), before); +} + +#[test] +fn graph_design_art_counts_toward_the_growth_allowance() { + TEST_GROWTH.with(|g| g.set(Some(20))); + let mut s = two_docs(); + for x in 0..30 { + s.execute("shape.rectangle", &rect(x)).unwrap(); + } + let before = state(&s); + let designs = |s: &Session| s.documents().iter().map(|d| d.doc.graph_designs.len()).collect::>(); + let designs_before = designs(&s); + // A design saved from the selection in an open document. + let e = run(&mut s, "vc.run('select.all'); vc.run('graph.design', {new: 'Many'});").unwrap_err().to_string(); + assert!(e.contains("objects and data"), "{e}"); + assert_eq!(state(&s), before); + assert_eq!(designs(&s), designs_before); + + // A document a run opens whose art is all in a graph design. + let mut maker = Session::new(); + maker.execute("file.new", &json!({})).unwrap(); + let ids: Vec = (0..30).map(|x| maker.execute("shape.rectangle", &rect(x)).unwrap()["id"].as_u64().unwrap()).collect(); + maker.execute("select.all", &json!({})).unwrap(); + maker.execute("graph.design", &json!({"new": "Many"})).unwrap(); + maker.execute("edit.clear", &json!({"ids": ids})).unwrap(); + assert_eq!(objects(&maker, 0), 0); + assert_eq!(maker.documents()[0].doc.graph_designs[0].art.count_with_masks(), 31); + let data = maker.execute("document.serialize", &json!({})).unwrap()["dataBase64"].as_str().unwrap().to_string(); + let source = format!("vc.run('document.open', {{name: 'g.vectorcraft', dataBase64: '{data}'}});"); + let e = run(&mut s, &source).unwrap_err().to_string(); + TEST_GROWTH.with(|g| g.set(None)); + assert!(e.contains("objects and data"), "{e}"); + assert_eq!(state(&s), before); +} + +/// Drops `v` one level at a time. +fn drop_flat(v: Value) { + let mut stack = vec![v]; + while let Some(mut v) = stack.pop() { + match &mut v { + Value::Object(o) => stack.extend(std::mem::take(o).into_iter().map(|(_, x)| x)), + Value::Array(a) => stack.append(a), + _ => {} + } + } +} + +#[test] +fn args_nested_ten_thousand_deep_in_a_script_throw_a_range_error_with_their_place() { + let mut s = two_docs(); + let before = state(&s); + let source = "var v = 1; for (var i = 0; i < 10000; i++) v = {a: v}; var m = 'none'; \ + try { vc.run('script.run', {source: '', args: v}); } catch (e) { m = e.name + '|' + e.message; } vc.log(m);"; + let r = run(&mut s, source).unwrap(); + let m = r["log"][0].as_str().unwrap_or_default(); + assert!(m.starts_with("RangeError|") && m.contains(".args.a.a.a") && m.contains("nested too deep"), "{r}"); + assert_eq!(state(&s), before); +} + +#[test] +fn args_nested_ten_thousand_deep_from_a_caller_are_refused_with_their_place() { + let mut s = two_docs(); + let before = state(&s); + // Built by moving each level in: `json!` would copy the value through `to_value`, one call per level. + let wrap = |key: &str, v: Value| Value::Object(std::iter::once((key.to_string(), v)).collect()); + let mut deep = json!(1); + for _ in 0..10_000 { + deep = wrap("a", deep); + } + let mut params = wrap("args", wrap("b", deep)); + params["source"] = json!(""); + let e = s.execute("script.run", ¶ms).unwrap_err().to_string(); + drop_flat(params); + assert!(e.contains("`args.b.a.a.a") && e.contains("nested more than 64 levels deep"), "{e}"); + assert_eq!(state(&s), before); +} + +#[test] +fn a_person_can_let_a_growing_run_go_on_or_stop_it() { + TEST_GROWTH.with(|g| g.set(Some(20))); + let run_to_the_question = |s: &mut Session| { + s.script_frames = true; + run(s, "for (var i = 0; i < 25; i++) vc.run('shape.rectangle', {x:i,y:1,width:1,height:1});").unwrap(); + let slices = Cell::new(0); + while !s.script_waiting() { + assert!(s.script_pump().is_none()); + slices.set(slices.get() + 1); + assert!(slices.get() < 1_000); + } + // Waiting takes no fuel, however often the frame comes round. + assert!(s.script_pump().is_none()); + }; + let mut s = two_docs(); + run_to_the_question(&mut s); + s.script_continue(); + assert!(!s.script_waiting()); + let done = loop { + if let Some(r) = s.script_pump() { + break r; + } + }; + assert_eq!(done.unwrap()["ok"], true); + assert_eq!(objects(&s, 1), 26); + + let mut s = two_docs(); + let before = state(&s); + run_to_the_question(&mut s); + assert_eq!(s.execute("script.stop", &json!({})).unwrap()["stopped"], true); + assert!(!s.script_waiting()); + assert!(s.script_pump().unwrap().is_err()); + TEST_GROWTH.with(|g| g.set(None)); + assert_eq!(state(&s), before); +} + +#[test] +fn a_file_saved_before_a_failure_stays_written_and_is_named() { + let path = std::env::temp_dir().join(format!("vc-script-save-{}.svg", std::process::id())); + let _ = std::fs::remove_file(&path); + let p = path.to_string_lossy().into_owned(); + let mut s = two_docs(); + let before = state(&s); + let source = + format!("vc.run('file.saveAs', {{path: {p:?}}}); vc.run('shape.rectangle', {{x:1,y:1,width:1,height:1}}); throw new Error('later');"); + let e = run(&mut s, &source).unwrap_err().to_string(); + assert!(path.exists()); + assert!(e.contains(&p), "{e}"); + assert_eq!(s.script_report().unwrap()["written"], json!([p])); + assert_eq!(state(&s), before, "the document does not keep the new path"); + let _ = std::fs::remove_file(&path); +} + +#[test] +fn a_committed_run_exports_what_it_drew() { + let path = std::env::temp_dir().join(format!("vc-script-export-{}.svg", std::process::id())); + let _ = std::fs::remove_file(&path); + let p = path.to_string_lossy().into_owned(); + let mut s = Session::new(); + s.execute("file.new", &json!({})).unwrap(); + let source = "for (var i = 0; i < 7; i++) vc.run('shape.rectangle', {x:i*20,y:5,width:10,height:10});"; + run(&mut s, source).unwrap(); + s.execute("document.save", &json!({"path": p})).unwrap(); + let svg = std::fs::read_to_string(&path).unwrap(); + assert_eq!(svg.matches(" impl proptest::strategy::Strategy { + use proptest::prelude::*; + let piece = prop_oneof![ + Just("vc.run('shape.rectangle', {x:1,y:1,width:5,height:5});".to_string()), + Just("vc.run('select.all'); vc.run('edit.clear');".to_string()), + Just("vc.run('file.new', {});".to_string()), + Just("vc.run('document.activate', {index:0});".to_string()), + Just("vc.run('no.such');".to_string()), + Just("vc.log(vc.document);".to_string()), + Just("throw new Error('x');".to_string()), + Just("vc.run('shape.rectangle', {x:2,y:2,width:5,height:5}); throw new Error('y');".to_string()), + Just("while (true) {}".to_string()), + Just("var o = {}; o.o = o; vc.run('shape.rectangle', o);".to_string()), + Just("{".to_string()), + Just("try {".to_string()), + Just("} catch (e) {}".to_string()), + "[ -~]{0,30}", + "\\PC{0,10}", + ]; + proptest::collection::vec(piece, 0..12).prop_map(|p| p.concat()) +} + +/// Every field of each open document but its next id, and the rest of what a rollback puts back. +/// A failed run raises the next id past the ids it gave out, which [`next_ids`] reads. +fn saved(s: &Session) -> (Value, Vec) { + let docs = s + .documents() + .iter() + .map(|d| { + let mut doc = (*d.doc).clone(); + doc.raise_next_id(1 << 50); + format!("{doc:?}") + }) + .collect(); + (state(s), docs) +} + +fn next_ids(s: &Session) -> Vec { + s.documents().iter().map(|d| d.doc.peek_next_id()).collect() +} + +proptest::proptest! { + #![proptest_config(proptest::prelude::ProptestConfig::with_cases(48))] + + /// Any script text ends with a report or a script error, and a run that fails leaves every + /// document as it was. + #[test] + fn any_source_ends_with_a_report_or_a_script_error(source in source_text()) { + let mut s = two_docs(); + let (before, ids) = (saved(&s), next_ids(&s)); + match s.execute("script.run", &json!({"source": source, "maxFuel": 200_000})) { + Ok(r) => proptest::prop_assert_eq!(&r["ok"], &json!(true), "{}", r), + Err(e) => { + proptest::prop_assert!(matches!(e, EngineError::Other(_)), "{:?}", e); + let kind = s.script_report.as_ref().map(|r| r["kind"].clone()); + proptest::prop_assert!(kind.as_ref().is_some_and(|k| k != "internal"), "{:?}: {}", kind, e); + proptest::prop_assert_eq!(saved(&s), before); + proptest::prop_assert!(next_ids(&s).iter().zip(&ids).all(|(after, was)| after >= was), "{:?} after {:?}", next_ids(&s), ids); + } + } + } +} diff --git a/crates/engine/src/tests/stylelib.rs b/crates/engine/src/tests/stylelib.rs index 31ceb24341..43838ff8e0 100644 --- a/crates/engine/src/tests/stylelib.rs +++ b/crates/engine/src/tests/stylelib.rs @@ -38,10 +38,11 @@ fn rect(s: &mut Session, x: f64, y: f64, w: f64, h: f64) -> NodeId { #[test] fn builtin_libraries_are_listed_with_original_styles_using_catalogued_effects() { - let mut s = Session::new(); + let mut s = session(); let list = run(&mut s, "graphicStyle.libraries", json!({})); let libs = list["libraries"].as_array().unwrap(); - assert!(libs.len() >= 6 && libs.iter().all(|l| l["category"] == "builtIn"), "{libs:?}"); + assert!(libs.len() >= 7 && libs.iter().all(|l| l["category"] == "builtIn"), "{libs:?}"); + assert!(libs.iter().any(|l| l["id"] == "game-hud" && l["name"] == "Game HUD"), "{libs:?}"); for l in libs { let id = l["id"].as_str().unwrap(); let g = run(&mut s, "graphicStyle.library", json!({"library": id})); @@ -56,6 +57,16 @@ fn builtin_libraries_are_listed_with_original_styles_using_catalogued_effects() } } } + let game = run(&mut s, "graphicStyle.library", json!({"library": "game-hud"})); + let game_names: Vec<&str> = game["styles"].as_array().unwrap().iter().map(|x| x["name"].as_str().unwrap()).collect(); + assert_eq!(game_names, ["Health Fill", "Mana Glow", "Damage Flash", "Quest Outline", "Coin Shine", "Boss Alert"]); + let id = rect(&mut s, 10.0, 20.0, 40.0, 30.0); + let r = run(&mut s, "graphicStyle.addFromLibrary", json!({"library": "game-hud", "name": "Mana Glow", "apply": true, "ids": [id.0]})); + assert_eq!((names(&r["added"]), r["applied"].as_str()), (vec!["Mana Glow"], Some("Mana Glow"))); + let node = doc(&s).node(id).unwrap(); + assert_eq!(node.appearance.fill_paint(), Paint::solid(vectorcraft_color::Color::from_hex("#3498db").unwrap())); + assert_eq!(node.appearance.stroke_paint(), Paint::None); + assert_eq!(node.appearance.effects.iter().map(|e| e.id.as_str()).collect::>(), ["stylize.outerGlow"]); // By name in any case. assert_eq!(run(&mut s, "graphicStyle.library", json!({"library": "shadows and glows"}))["id"], "shadows-glows"); assert!(s.execute("graphicStyle.library", &json!({"library": "nope"})).is_err()); diff --git a/crates/engine/src/tests/symbollib.rs b/crates/engine/src/tests/symbollib.rs index 42909da1c7..410bd473da 100644 --- a/crates/engine/src/tests/symbollib.rs +++ b/crates/engine/src/tests/symbollib.rs @@ -84,12 +84,16 @@ fn the_builtin_library_is_original_art_generated_in_code() { let mut s = Session::new(); let list = run(&mut s, "symbol.libraries", json!({})); let libs = list["libraries"].as_array().unwrap(); - assert_eq!(libs.len(), 2, "{libs:?}"); + assert_eq!(libs.len(), 3, "{libs:?}"); assert_eq!((libs[0]["id"].as_str(), libs[0]["category"].as_str()), (Some("basic-shapes"), Some("builtIn"))); assert_eq!( (libs[1]["id"].as_str(), libs[1]["name"].as_str(), libs[1]["category"].as_str()), (Some("ui-frames"), Some("UI Frames"), Some("builtIn")) ); + assert_eq!( + (libs[2]["id"].as_str(), libs[2]["name"].as_str(), libs[2]["category"].as_str()), + (Some("map-markers"), Some("Map Markers"), Some("builtIn")) + ); let lib = run(&mut s, "symbol.library", json!({"library": "basic shapes"})); let names: Vec<&str> = lib["symbols"].as_array().unwrap().iter().map(|x| x["name"].as_str().unwrap()).collect(); assert_eq!(names, ["Circle", "Square", "Rounded Square", "Triangle", "Diamond", "Hexagon", "Star", "Burst", "Arrow"]); @@ -125,6 +129,32 @@ fn ui_frames_symbols_carry_default_nine_slice_when_added() { )); } +#[test] +fn map_markers_symbols_add_without_nine_slice() { + let mut s = session(); + let lib = run(&mut s, "symbol.library", json!({"library": "map-markers"})); + let names: Vec<&str> = lib["symbols"].as_array().unwrap().iter().map(|x| x["name"].as_str().unwrap()).collect(); + assert_eq!(names, ["Pin", "Flag", "Crosshair", "Checkpoint"]); + let mut placed = Vec::new(); + for (i, name) in names.iter().enumerate() { + let r = run( + &mut s, + "symbol.addFromLibrary", + json!({"library": "map-markers", "name": name, "place": true, "x": 100.0 + 80.0 * i as f64, "y": 100.0}), + ); + assert_eq!(r["added"], json!([name])); + placed.push(r["placed"].as_u64().unwrap()); + } + let d = doc(&s); + for name in &names { + assert_eq!(d.symbol_nine_slice(name), None, "{name} should not carry 9-slice guides"); + } + assert!(matches!( + d.node(NodeId(placed[0])).map(|n| &n.kind), + Some(NodeKind::SymbolInstance { symbol, .. }) if symbol == "Pin" + )); +} + #[test] fn a_saved_library_reopens_and_its_symbols_join_another_document_in_one_step() { let dir = folder("user"); diff --git a/crates/engine/src/tooling.rs b/crates/engine/src/tooling.rs index e818c36862..13fb87ccd4 100644 --- a/crates/engine/src/tooling.rs +++ b/crates/engine/src/tooling.rs @@ -456,6 +456,9 @@ impl Session { /// applied, in order ([`Session::tool_poll`]); moves of the pointer with no button held go to /// the tool at once. pub fn pointer(&mut self, ev: &PointerEvent, view: ViewInfo) -> Result> { + if self.script_running() { + return if ev.kind == PointerKind::Move { Ok(vec![]) } else { Err(EngineError::Busy) }; + } let n = self.next_input(); if ev.kind != PointerKind::Move && (!self.held_input.is_empty() || self.tool_edit_pending()) { self.held_input.push_back((n, HeldInput::Pointer(*ev), view)); @@ -878,6 +881,9 @@ impl Session { /// A key for the active tool. While the tool computes an edit on another thread, the key is held /// and made once the edit is applied, after the input held before it. pub fn tool_key(&mut self, key: ToolKey, mods: Mods, view: ViewInfo) -> Result> { + if self.script_running() { + return Err(EngineError::Busy); + } let n = self.next_input(); if self.tool_editing() { self.held_input.push_back((n, HeldInput::Key(key, mods), view)); @@ -911,6 +917,9 @@ impl Session { /// Typed text for the active tool (Type tool). pub fn tool_text(&mut self, text: &str, view: ViewInfo) -> Result> { + if self.script_running() { + return Err(EngineError::Busy); + } let acts = self.with_tool_cx(view, |t, cx| t.text_input(cx, text)); self.take_tool_panic()?; self.apply_actions(acts) @@ -1060,6 +1069,12 @@ impl Session { self.plane_key(key).is_some() || self.with_tool_cx(view, |t, cx| t.claims_key(cx, key)) } + /// Has the active tool started something that Escape ends while no button is pressed (see + /// `Tool::ends_on_escape`)? + pub fn tool_ends_on_escape(&mut self, view: ViewInfo) -> bool { + self.with_tool_cx(view, |t, cx| t.ends_on_escape(cx)) + } + pub fn overlays(&mut self, view: ViewInfo) -> Vec { // The Blend tool's first pick is not marked after an edit that dropped it. self.tell_tool_history_moved(); diff --git a/crates/eps/src/import/ai.rs b/crates/eps/src/import/ai.rs index b353a00887..5f4a5b6314 100644 --- a/crates/eps/src/import/ai.rs +++ b/crates/eps/src/import/ai.rs @@ -37,6 +37,8 @@ use crate::ps; pub(crate) use envelope::DRAWN as ENVELOPE_DRAWN; #[cfg(test)] pub(crate) use envelope::MAX_CHECKED; +#[cfg(test)] +pub(crate) use envelope::TYPE_DRAWN as ENVELOPE_TYPE_DRAWN; pub(crate) use envelope::{WARPED_TYPE_DRAWN, WarpedType}; pub(crate) use frames::text_frames; pub use obj::{NameEncoding, Names}; diff --git a/crates/eps/src/import/ai/envelope.rs b/crates/eps/src/import/ai/envelope.rs index a421bbd6a3..3368a97be6 100644 --- a/crates/eps/src/import/ai/envelope.rs +++ b/crates/eps/src/import/ai/envelope.rs @@ -35,12 +35,15 @@ use vectorcraft_doc::{Appearance, Document, Effect, ImageBlob, LayerColor, Node, use vectorcraft_geom::PathData; use super::obj::Obj; -use crate::import::native::compare::{MAX_DIFFERENCE, MAX_SOLID_DIFFERENCE, compare_scale, differ, differ_in_colour}; +use crate::import::native::compare::{MAX_DIFFERENCE, MAX_SOLID_DIFFERENCE, compare_scale, differ, differ_in_colour, differ_on_black}; /// The plugin that writes envelopes. pub(super) const PLUGIN: &str = "Adobe Deform Plugin"; // brand-ok: the plugin name the files use /// The note for an envelope that keeps its drawn art. pub(crate) const DRAWN: &str = "an envelope VectorCraft couldn't read as a live envelope comes in as its drawn art"; +/// The note for an envelope of type, which keeps its drawn art with its type hidden (unless the +/// text document gives the type nothing, which a note of its own then says). +pub(crate) const TYPE_DRAWN: &str = "type in an envelope comes in as the envelope's drawn art, not as editable type"; /// The note for warped type that keeps its drawn art, before how many. pub(crate) const WARPED_TYPE_DRAWN: &str = "warped text objects that came in as drawn art, not as editable type"; /// The most envelopes waiting for their drawn art at once. @@ -325,9 +328,9 @@ fn alone(node: &Node, layer: NodeId, shared: &Shared<'_>) -> Document { } /// How `live` and `drawn`, drawn over `region` at `scale`, differ: the pixels that differ in -/// lightness or colour, those whose neighbours all differ too (where one draws something the other -/// doesn't, not an edge drawn a little apart), and the pixels either inks. `None` when they can't -/// be drawn. +/// lightness or colour, seen on white or on black (each is drawn on its own: white art shows only on +/// black), those whose neighbours all differ too (where one draws something the other doesn't, not +/// an edge drawn a little apart), and the pixels either inks. `None` when they can't be drawn. fn differing(live: &Document, drawn: &Document, region: Rect, scale: f64) -> Option<(usize, usize, usize)> { let x = vectorcraft_render::Renderer::new().render_region(live, region, scale, false); let y = vectorcraft_render::Renderer::new().render_region(drawn, region, scale, false); @@ -336,7 +339,7 @@ fn differing(live: &Document, drawn: &Document, region: Rect, scale: f64) -> Opt } let (w, h) = (x.width as usize, x.height as usize); let (xs, ys) = (x.pixels.as_chunks::<4>().0, y.pixels.as_chunks::<4>().0); - let differs: Vec = xs.iter().zip(ys).map(|(p, q)| differ(p, q) || differ_in_colour(p, q)).collect(); + let differs: Vec = xs.iter().zip(ys).map(|(p, q)| differ(p, q) || differ_in_colour(p, q) || differ_on_black(p, q)).collect(); let inked = xs.iter().zip(ys).filter(|(p, q)| p[3] > 8 || q[3] > 8).count(); let at = |i: usize, j: usize| differs.get(j * w + i).copied().unwrap_or(false); let any = differs.iter().filter(|d| **d).count(); diff --git a/crates/eps/src/import/ai/read/containers.rs b/crates/eps/src/import/ai/read/containers.rs index 35c0f46ae6..3de4daadfb 100644 --- a/crates/eps/src/import/ai/read/containers.rs +++ b/crates/eps/src/import/ai/read/containers.rs @@ -519,6 +519,7 @@ impl<'a> Reader<'a> { // An envelope of type keeps its drawn art and its type, hidden, as above: the // type is filled in after reading, which the envelope can't wait for. if typed { + self.warn(crate::import::ai::envelope::TYPE_DRAWN); return Ok(()); } if self.envelopes.len() >= crate::import::ai::envelope::MAX_PENDING { diff --git a/crates/eps/src/import/ai/tests.rs b/crates/eps/src/import/ai/tests.rs index 19cd6fa279..2f0fca73be 100644 --- a/crates/eps/src/import/ai/tests.rs +++ b/crates/eps/src/import/ai/tests.rs @@ -7826,6 +7826,23 @@ fn an_envelope_that_doesnt_come_out_as_drawn_keeps_its_drawn_art() { assert_eq!(r.warnings, [super::envelope::DRAWN]); } +/// The same, in white: white art seen on white looks like nothing, so the check sees it on black +/// too, and a white envelope that draws elsewhere keeps its drawn art. +#[test] +fn a_white_envelope_that_doesnt_come_out_as_drawn_keeps_its_drawn_art() { + use vectorcraft_doc::live::EnvelopeKind; + const WHITE: &str = "0 0 0 0 1 1 1 Xa\n"; + let other = EnvelopeKind::Warp { style: "arc".into(), bend: -50.0, h: 0.0, v: 0.0, horizontal: true }; + let content = envelope_content().replace(RED, WHITE); + let drawn = drawn_content(&other).replace(RED, WHITE); + let body = envelope_of(&straight_mesh(1, 1, (120.0, 60.0)), &warp_keys(1, 0.5, 0.0, 0.0, 0), &content, 1, &drawn); + let r = read_ok(&layer(&body)); + let a = art(&r.doc); + assert_eq!(a.len(), 1, "{a:#?}"); + assert!(matches!(a[0].kind, NodeKind::Group { .. }), "{a:#?}"); + assert_eq!(r.warnings, [super::envelope::DRAWN]); +} + /// A document of `n` warped text objects, with the art the live warp makes of each, in its look. fn warped_type_doc(n: usize) -> (Document, Vec) { use vectorcraft_doc::{Appearance, Effect, TextObject}; @@ -7871,6 +7888,36 @@ fn warped_type_past_the_budget_comes_in_as_its_look() { assert_eq!(kept.extras().wrap, Some(wrap)); } +/// White warped type is checked as other type is: seen on white it looks like nothing, so the check +/// sees it on black too. Type whose live warp draws as its look stays type; type whose look is +/// warped the other way comes in as its look. +#[test] +fn white_warped_type_that_draws_elsewhere_comes_in_as_its_look() { + use vectorcraft_doc::{Appearance, CharStyle, Effect, TextObject}; + let warp = |bend: f64| { + let mut appearance = Appearance::default(); + appearance.effects.push(Effect { id: "warp.arc".into(), params: serde_json::json!({"bend": bend}), visible: true }); + appearance + }; + for (look_bend, replaced) in [(40.0, 0), (-40.0, 1)] { + let mut doc = Document::new(400.0, 200.0); + let mut layer = Node::layer(doc.alloc_id(), "Art", vectorcraft_doc::LayerColor::Preset(0)); + let white = CharStyle { fill: Paint::solid(Color::WHITE), ..Default::default() }; + let t = TextObject::point(kurbo::Point::new(20.0, 60.0), "TILT", white); + let mut text = Node::new(doc.alloc_id(), NodeKind::Text(Box::new(t))); + text.appearance = warp(40.0).into(); + let mut other = text.clone(); + other.appearance = warp(look_bend).into(); + let mut look = vectorcraft_effects::expand_outlined(None, &other, None).unwrap(); + look.id = doc.alloc_id(); + let looks = vec![super::envelope::WarpedLook { slot: text.id, look, left_out: None }]; + layer.children_mut().unwrap().push(Arc::new(text)); + doc.layers = vec![Arc::new(layer)]; + let warped = super::envelope::WarpedType { looks, checks: 1, ..Default::default() }; + assert_eq!(warped.settle(&mut doc, Some, &Default::default(), &mut vec![]), replaced, "look bent {look_bend}"); + } +} + /// The budget for warped type is what the envelopes left: their checks and the page's share they /// spent, with the page they are held to. #[test] diff --git a/crates/eps/src/import/native/compare.rs b/crates/eps/src/import/native/compare.rs index 044dbd2401..99cafb771c 100644 --- a/crates/eps/src/import/native/compare.rs +++ b/crates/eps/src/import/native/compare.rs @@ -56,6 +56,15 @@ pub(in crate::import) fn differ(p: &[u8; 4], q: &[u8; 4]) -> bool { lightness(p).abs_diff(lightness(q)) > SAME_PIXEL || (a.min(b) <= WHITE && a.abs_diff(b) > SAME_PIXEL) } +/// Do two pixels look different seen on black: in lightness? An object drawn on its own and seen +/// only on white hides what it draws in white (white type over nothing looks like nothing): seen +/// on black too, that shows. +pub(in crate::import) fn differ_on_black(p: &[u8; 4], q: &[u8; 4]) -> bool { + // Premultiplied, a pixel is what it shows on black. + let on_black = |p: &[u8; 4]| [0, 1, 2].map(|i| u32::from(p[i])); + p != q && lightness(on_black(p)).abs_diff(lightness(on_black(q))) > SAME_PIXEL +} + /// How far apart two pixels' red, green or blue may be for them to be the same colour (a colour /// and its CMYK equivalent stay within it; a red and a dark red don't). const SAME_COLOUR: u32 = 64; diff --git a/crates/eps/src/import/tests_native.rs b/crates/eps/src/import/tests_native.rs index 13f979f9f8..9317176551 100644 --- a/crates/eps/src/import/tests_native.rs +++ b/crates/eps/src/import/tests_native.rs @@ -5222,7 +5222,8 @@ fn envelope_options_keep_the_source_text_hidden_under_its_outlined_appearance() } }); assert_eq!(texts, [("CHONKYCATS".to_string(), false)], "{:?}", r.warnings); - assert!(super::tests::program_warnings(&r.warnings).is_empty(), "{:?}", r.warnings); + // The notes say the type isn't editable. + assert_eq!(super::tests::program_warnings(&r.warnings), [crate::import::ai::ENVELOPE_TYPE_DRAWN], "{:?}", r.warnings); } /// A live envelope that draws a little apart from its drawn art, in layers that already differ diff --git a/crates/format/src/atomic.rs b/crates/format/src/atomic.rs index c208f1b524..863c6fdd34 100644 --- a/crates/format/src/atomic.rs +++ b/crates/format/src/atomic.rs @@ -10,7 +10,8 @@ //! is left as it was and the save fails. //! //! On macOS `File::sync_all` is a full flush (`F_FULLFSYNC`), which SMB shares refuse with -//! `ENOTSUP` while a plain `fsync` works: [`sync_file`] falls back to the plain one there (#1620). +//! `ENOTSUP` and virtiofs shares (folders shared into a macOS VM) with `ENOTTY`, while a plain +//! `fsync` works: [`sync_file`] falls back to the plain one there (#1620). use std::fs::{File, OpenOptions}; use std::io::{self, Write as _}; @@ -180,8 +181,9 @@ fn copy_new(from: &Path, path: &Path) -> io::Result<()> { } /// Flush `file` to stable storage (`sync_all`). On Apple platforms that is a full flush -/// (`F_FULLFSYNC`); where the volume refuses it with `ENOTSUP` (SMB shares, #1620) this falls back -/// to a plain `fsync`. Any other error, and a failed `fsync`, is returned as it is. +/// (`F_FULLFSYNC`); where the volume refuses it with `ENOTSUP` (SMB shares) or `ENOTTY` (virtiofs +/// shares, #1620) this falls back to a plain `fsync`. Any other error, and a failed `fsync`, is +/// returned as it is. pub fn sync_file(file: &File) -> io::Result<()> { match full_sync(file) { Err(e) if full_flush_unsupported(&e) => plain_fsync(file), @@ -190,9 +192,10 @@ pub fn sync_file(file: &File) -> io::Result<()> { } /// Whether `e` is a volume refusing a full flush. Never off Apple platforms: there `sync_all` is -/// already a plain `fsync`. Checked by its code because std maps `ENOTSUP` to `Uncategorized`. +/// already a plain `fsync`. Checked by its code because std maps `ENOTSUP` and `ENOTTY` to +/// `Uncategorized`. fn full_flush_unsupported(e: &io::Error) -> bool { - cfg!(target_vendor = "apple") && e.raw_os_error() == Some(ENOTSUP) + cfg!(target_vendor = "apple") && matches!(e.raw_os_error(), Some(ENOTSUP | ENOTTY)) } #[cfg(target_vendor = "apple")] @@ -232,6 +235,9 @@ fn full_sync(file: &File) -> io::Result<()> { const ENOTSUP: i32 = 45; #[cfg(not(target_vendor = "apple"))] const ENOTSUP: i32 = 95; +/// What macOS answers when a virtiofs share (a folder shared into a VM) is asked for a full flush. +/// The same number on every Unix. +const ENOTTY: i32 = 25; #[cfg(test)] thread_local! { @@ -414,6 +420,17 @@ mod tests { let _ = std::fs::remove_dir_all(&d); } + /// A save to a virtiofs share (#1620: a folder shared into a macOS VM): macOS refuses the full + /// flush there with `ENOTTY` (os error 25), which falls back to a plain `fsync` as `ENOTSUP` does. + /// Elsewhere neither is a refused full flush, and other errors never are. + #[test] + fn a_full_flush_refused_with_enotty_falls_back_like_enotsup() { + let apple = cfg!(target_vendor = "apple"); + assert_eq!(full_flush_unsupported(&io::Error::from_raw_os_error(25)), apple, "ENOTTY"); + assert_eq!(full_flush_unsupported(&io::Error::from_raw_os_error(ENOTSUP)), apple, "ENOTSUP"); + assert!(!full_flush_unsupported(&io::Error::other("the connection was lost"))); + } + fn denied() -> io::Result { Err(io::Error::new(io::ErrorKind::PermissionDenied, "refused by the share")) } diff --git a/crates/js/src/builtins.rs b/crates/js/src/builtins.rs index 984d3a1236..d420b94b31 100644 --- a/crates/js/src/builtins.rs +++ b/crates/js/src/builtins.rs @@ -501,7 +501,7 @@ fn function_to_string(interp: &mut Interp, this: Value, _: &[Value], _: bool) -> return Ok(Value::String(Str::from_units(units.to_vec()))); } Some(Func::Native { name, .. }) => format!("function {name}() {{ [native code] }}"), - Some(Func::Host { name, .. }) => format!("function {name}() {{ [native code] }}"), + Some(Func::Host { name, .. } | Func::Data { name, .. }) => format!("function {name}() {{ [native code] }}"), Some(Func::Bound { .. }) => "function () { [native code] }".to_string(), None => return Err(interp.type_error("Function.prototype.toString was called on a value that is not a function")), }; diff --git a/crates/js/src/heap.rs b/crates/js/src/heap.rs index 1b2099fe16..a53721fc71 100644 --- a/crates/js/src/heap.rs +++ b/crates/js/src/heap.rs @@ -158,6 +158,9 @@ pub(crate) type NativeFn = fn(&mut crate::interp::Interp, Value, &[Value], bool) /// A function the embedding defines. pub(crate) type HostFn = dyn Fn(&[crate::JsValue]) -> Result; +/// A function the embedding defines that takes and gives structured values. +pub(crate) type DataFn = crate::host::HostFunction; + /// The built-ins the interpreter treats specially when it calls them. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub(crate) enum NativeKind { @@ -177,6 +180,7 @@ pub(crate) enum Func { Closure { code: Rc, env: EnvId }, Native { f: NativeFn, kind: NativeKind, constructor: bool, name: &'static str }, Host { f: Rc, name: Rc }, + Data { f: DataFn, name: Rc }, Bound { target: ObjId, this: Value, args: Rc<[Value]> }, } diff --git a/crates/js/src/host.rs b/crates/js/src/host.rs new file mode 100644 index 0000000000..457b2ce2e1 --- /dev/null +++ b/crates/js/src/host.rs @@ -0,0 +1,351 @@ +//! Structured values between a script and its host: [`Data`] (JSON's shapes and `undefined`), the +//! checks a value passes on its way across, and the frozen objects a host adds to the global +//! environment. +//! +//! A value read from a script may hold plain objects, arrays, strings, finite numbers, booleans, +//! `null` and `undefined`. A cycle, a value too deep or too large, a function, a getter, a date, a +//! regular expression, a boxed primitive, a hole in an array and a number that is not finite are +//! refused with a `TypeError` or `RangeError` naming where the value is. The same object may appear +//! more than once when it is not its own ancestor; each appearance counts against the size limit, +//! so sharing cannot multiply the work without limit. + +use std::rc::Rc; + +use crate::LimitKind; +use crate::heap::{Class, ENUMERABLE, Func, Key, OBJECT_BYTES, ObjId, Object, PROP_BYTES, Prop, key, string_bytes}; +use crate::interp::{Abrupt, ErrorType, Interp, JsResult}; +use crate::value::{Value, index_key}; + +/// A value that crosses between a script and the host. +#[derive(Clone, Debug, PartialEq)] +pub enum Data { + Undefined, + Null, + Bool(bool), + Number(f64), + String(String), + Array(Vec), + /// An object's own enumerable properties, in the order the object lists them. + Object(Vec<(String, Data)>), +} + +/// How much one crossing may carry. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct DataLimits { + /// How deeply arrays and objects may nest. + pub depth: usize, + /// Estimated bytes of the strings, names and numbers. + pub bytes: usize, + /// Array elements and object properties, all of them counted together. + pub entries: usize, +} + +impl Default for DataLimits { + fn default() -> Self { + Self { depth: 64, bytes: 16 << 20, entries: 1 << 20 } + } +} + +/// How a host function fails. +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum HostError { + /// Thrown to the script as an `Error`; the script can catch it. + Error(String), + /// Thrown to the script as a `TypeError`. + Type(String), + /// Thrown to the script as a `RangeError`. + Range(String), + /// Ends the run with [`LimitKind::Host`] and this message. The script cannot catch it. + Abort(String), +} + +/// A function the host gives a script, with its arguments converted. +pub type HostFunction = Rc) -> Result>; + +/// A member of an object the host adds to the global environment. +#[derive(Clone)] +pub enum HostItem { + /// A read-only copy of a value. + Value(Data), + Function(HostFunction), + /// A property whose value the function gives each time it is read. + Getter(HostFunction), + /// A frozen object with these members. + Object(Vec<(String, HostItem)>), +} + +enum Step { + Name(Key), + Index(u32), +} + +/// A value being read: what it has used so far, and where the reader is. +struct Reading { + limits: DataLimits, + bytes: usize, + entries: usize, + ancestors: Vec, + path: Vec, + function: Rc, +} + +impl Reading { + fn place(&self) -> String { + let mut s = String::new(); + for step in &self.path { + match step { + Step::Index(i) => s.push_str(&format!("[{i}]")), + Step::Name(k) => { + s.push('.'); + s.push_str(&String::from_utf16_lossy(k)); + } + } + } + s + } +} + +enum Shape { + Array(u32), + Plain(Vec<(Key, Prop)>), +} + +impl Interp { + fn data_error(&mut self, r: &Reading, t: ErrorType, what: &str) -> Abrupt { + let message = format!("{}: argument{} {what}", r.function, r.place()); + self.throw(t, &message) + } + + fn charge_reading(&mut self, r: &mut Reading, bytes: usize) -> JsResult<()> { + r.bytes = r.bytes.saturating_add(bytes); + if r.bytes > r.limits.bytes { + return Err(self.data_error(r, ErrorType::Range, "is too large")); + } + Ok(()) + } + + fn charge_entries(&mut self, r: &mut Reading, n: usize) -> JsResult<()> { + r.entries = r.entries.saturating_add(n); + if r.entries > r.limits.entries { + return Err(self.data_error(r, ErrorType::Range, "has too many entries")); + } + Ok(()) + } + + fn read_data(&mut self, v: &Value, r: &mut Reading) -> JsResult { + match v { + Value::Undefined => Ok(Data::Undefined), + Value::Null => Ok(Data::Null), + Value::Bool(b) => Ok(Data::Bool(*b)), + Value::Number(n) if n.is_finite() => Ok(Data::Number(*n)), + Value::Number(_) => Err(self.data_error(r, ErrorType::Type, "is not a finite number")), + Value::String(s) => { + self.charge_reading(r, s.len().saturating_mul(3).saturating_add(2))?; + Ok(Data::String(s.to_rust_string())) + } + Value::Object(id) => self.read_object(*id, r), + } + } + + fn read_object(&mut self, id: ObjId, r: &mut Reading) -> JsResult { + self.use_fuel()?; + if r.ancestors.contains(&id) { + return Err(self.data_error(r, ErrorType::Type, "refers to itself")); + } + if r.ancestors.len() >= r.limits.depth { + return Err(self.data_error(r, ErrorType::Range, "is nested too deep")); + } + let shape = match &self.object(id)?.class { + Class::Array { length, .. } => Shape::Array(*length), + Class::Ordinary => { + let o = self.object(id)?; + if o.props.len() > r.limits.entries { + return Err(self.data_error(r, ErrorType::Range, "has too many entries")); + } + Shape::Plain(o.props.iter().filter(|(_, p)| p.enumerable()).map(|(k, p)| (k.clone(), p.clone())).collect()) + } + other => { + let what = format!("is a {}, not plain data", other.name()); + return Err(self.data_error(r, ErrorType::Type, &what)); + } + }; + r.ancestors.push(id); + let out = match shape { + Shape::Array(length) => self.read_array(id, length, r), + Shape::Plain(props) => self.read_plain(props, r), + }; + r.ancestors.pop(); + out + } + + 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); + for i in 0..length { + self.use_fuel()?; + r.path.push(Step::Index(i)); + let prop = self.object(id)?.props.get(&index_key(i)).cloned(); + let item = match prop { + Some(Prop::Data { value: Value::Undefined, .. }) | None => Err(self.data_error(r, ErrorType::Type, "is undefined")), + Some(Prop::Data { value, .. }) => self.read_data(&value, r), + Some(Prop::Accessor { .. }) => Err(self.data_error(r, ErrorType::Type, "is a getter, not plain data")), + }?; + r.path.pop(); + items.push(item); + } + Ok(Data::Array(items)) + } + + fn read_plain(&mut self, props: Vec<(Key, Prop)>, r: &mut Reading) -> JsResult { + self.charge_entries(r, props.len())?; + let mut out = Vec::with_capacity(props.len()); + for (k, prop) in props { + self.use_fuel()?; + self.charge_reading(r, k.len().saturating_mul(3).saturating_add(8))?; + let name = String::from_utf16_lossy(&k); + r.path.push(Step::Name(k)); + let item = match prop { + // A property holding `undefined` reads as one left out. + Prop::Data { value: Value::Undefined, .. } => None, + Prop::Data { value, .. } => Some(self.read_data(&value, r)?), + Prop::Accessor { .. } => return Err(self.data_error(r, ErrorType::Type, "is a getter, not plain data")), + }; + r.path.pop(); + if let Some(item) = item { + out.push((name, item)); + } + } + Ok(Data::Object(out)) + } + + /// A host value as a JavaScript value, `frozen` when a script may not change it. A value + /// deeper or longer than the limits throws a `RangeError`. + pub(crate) fn write_data(&mut self, d: Data, depth: usize, frozen: bool) -> JsResult { + if depth > self.data_limits.depth { + return Err(self.throw(ErrorType::Range, "a host value is nested too deep")); + } + Ok(match d { + Data::Undefined => Value::Undefined, + Data::Null => Value::Null, + Data::Bool(b) => Value::Bool(b), + Data::Number(n) => Value::Number(n), + Data::String(s) => { + let bytes = string_bytes(s.encode_utf16().count()); + self.reserve_heap(bytes)?; + self.heap.bytes = self.heap.bytes.saturating_add(bytes); + Value::str(&s) + } + Data::Array(items) => { + self.write_container(items.into_iter().enumerate().map(|(i, d)| (Slot::Index(i), d)).collect(), true, depth, frozen)? + } + Data::Object(items) => self.write_container(items.into_iter().map(|(k, d)| (Slot::Name(k), d)).collect(), false, depth, frozen)?, + }) + } + + fn write_container(&mut self, items: Vec<(Slot, Data)>, array: bool, depth: usize, frozen: bool) -> JsResult { + if items.len() > self.data_limits.entries { + return Err(self.throw(ErrorType::Range, "a host value has too many entries")); + } + let flags = if frozen { ENUMERABLE } else { crate::heap::OPEN }; + self.reserve_heap(OBJECT_BYTES.saturating_add(PROP_BYTES.saturating_mul(items.len())))?; + let id = if array { + let proto = self.intrinsics.array_proto; + self.heap.alloc_object(Object::new(Class::Array { length: 0, length_writable: !frozen }, Some(proto))) + } else { + self.new_object() + }; + let mark = self.temp_roots.len(); + self.temp_roots.push(Value::Object(id)); + let mut result = Ok(()); + for (slot, d) in items { + let name = match slot { + Slot::Index(i) => index_key(u32::try_from(i).unwrap_or(u32::MAX)), + Slot::Name(n) => key(&n), + }; + result = self.write_data(d, depth + 1, frozen).and_then(|value| self.define(id, name, Prop::Data { value, flags })); + if result.is_err() { + break; + } + } + self.temp_roots.truncate(mark); + result?; + if frozen { + self.object_mut(id)?.extensible = false; + } + Ok(Value::Object(id)) + } + + /// Calls host function `f`: reads its arguments, runs it, and gives its result to the script. + pub(crate) fn call_data(&mut self, f: &crate::heap::DataFn, name: &Rc, args: &[Value]) -> JsResult { + let mut reading = Reading { limits: self.data_limits, bytes: 0, entries: 0, ancestors: Vec::new(), path: Vec::new(), function: name.clone() }; + let mut data = Vec::with_capacity(args.len()); + for (i, a) in args.iter().enumerate() { + reading.path.push(Step::Index(u32::try_from(i).unwrap_or(u32::MAX))); + data.push(self.read_data(a, &mut reading)?); + reading.path.pop(); + } + match f(data) { + Ok(d) => self.write_data(d, 0, false), + Err(HostError::Abort(message)) => { + self.host_abort = Some(message); + Err(Abrupt::Limit(LimitKind::Host)) + } + Err(HostError::Error(message)) => Err(self.throw_host(ErrorType::Error, &message)?), + Err(HostError::Type(message)) => Err(self.throw_host(ErrorType::Type, &message)?), + Err(HostError::Range(message)) => Err(self.throw_host(ErrorType::Range, &message)?), + } + } + + /// The exception for a host error, charged to the heap. + fn throw_host(&mut self, t: ErrorType, message: &str) -> JsResult { + let bytes = string_bytes(message.encode_utf16().count()); + self.reserve_heap(bytes)?; + self.heap.bytes = self.heap.bytes.saturating_add(bytes); + Ok(self.throw(t, message)) + } + + /// Adds the frozen object `name` with `items` to the global environment. + pub(crate) fn install_host_object(&mut self, name: &str, items: Vec<(String, HostItem)>) -> JsResult<()> { + let o = self.host_object(name, items)?; + let global = self.global; + self.define(global, key(name), Prop::Data { value: Value::Object(o), flags: 0 }) + } + + fn host_object(&mut self, path: &str, items: Vec<(String, HostItem)>) -> JsResult { + let o = self.new_object(); + let mark = self.temp_roots.len(); + self.temp_roots.push(Value::Object(o)); + let mut result = Ok(()); + for (name, item) in items { + result = self.install_item(o, path, name, item); + if result.is_err() { + break; + } + } + self.temp_roots.truncate(mark); + result?; + self.object_mut(o)?.extensible = false; + Ok(o) + } + + fn install_item(&mut self, o: ObjId, path: &str, name: String, item: HostItem) -> JsResult<()> { + let full = format!("{path}.{name}"); + let prop = match item { + HostItem::Value(d) => Prop::Data { value: self.write_data(d, 0, true)?, flags: ENUMERABLE }, + HostItem::Function(f) => Prop::Data { value: Value::Object(self.host_function(f, &full)), flags: ENUMERABLE }, + HostItem::Getter(f) => Prop::Accessor { get: Some(self.host_function(f, &full)), set: None, flags: ENUMERABLE }, + HostItem::Object(items) => Prop::Data { value: Value::Object(self.host_object(&full, items)?), flags: ENUMERABLE }, + }; + self.define(o, key(&name), prop) + } + + fn host_function(&mut self, f: HostFunction, name: &str) -> ObjId { + let proto = self.intrinsics.function_proto; + self.heap.alloc_object(Object::new(Class::Function(Func::Data { f, name: name.into() }), Some(proto))) + } +} + +enum Slot { + Index(usize), + Name(String), +} diff --git a/crates/js/src/host_tests.rs b/crates/js/src/host_tests.rs new file mode 100644 index 0000000000..85e178d879 --- /dev/null +++ b/crates/js/src/host_tests.rs @@ -0,0 +1,288 @@ +//! Resumable runs and the structured values host functions take and give. + +use std::cell::{Cell, RefCell}; +use std::rc::Rc; + +use super::*; + +fn realm(fuel: u64) -> Realm { + let mut r = Realm::new(); + r.set_limits(Limits { fuel, ..Limits::default() }); + r +} + +/// 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(); + let log = seen.clone(); + let f: HostFunction = Rc::new(move |mut args| { + let v = if args.is_empty() { Data::Undefined } else { args.remove(0) }; + log.borrow_mut().push(v.clone()); + Ok(v) + }); + r.define_host_object("host", vec![("take".into(), HostItem::Function(f))]).unwrap(); + seen +} + +fn finish(r: &mut Realm, slice: u64) -> (Result, u32) { + let mut slices = 0; + loop { + slices += 1; + match r.advance(slice) { + Ok(Progress::Paused) => {} + Ok(Progress::Done(v)) => return (Ok(v), slices), + Err(e) => return (Err(e), slices), + } + } +} + +#[test] +fn a_resumed_run_gives_the_result_of_one_run() { + let source = "var t = 0; for (var i = 0; i < 2000; i++) { t += i; } t"; + let whole = realm(10_000_000).run(source).unwrap(); + let mut r = realm(10_000_000); + r.start(source).unwrap(); + assert!(r.is_running()); + let (v, slices) = finish(&mut r, 100); + assert_eq!(v.unwrap(), whole); + assert!(slices > 10, "the run paused: {slices} slices"); + assert!(!r.is_running()); +} + +#[test] +fn state_survives_a_pause_and_a_collection_between_slices() { + let mut r = realm(10_000_000); + r.start("var o = {a: [1, 2, 3]}; var n = 0; for (var i = 0; i < 500; i++) { n += o.a.length; } n").unwrap(); + assert_eq!(r.advance(50).unwrap(), Progress::Paused); + r.collect_garbage(); + assert_eq!(finish(&mut r, 50).0.unwrap(), JsValue::Number(1500.0)); +} + +#[test] +fn the_fuel_limit_covers_every_slice_together() { + let mut r = realm(5_000); + r.start("while (true) {}").unwrap(); + let (v, slices) = finish(&mut r, 100); + assert!(matches!(v, Err(RunError { kind: RunErrorKind::Limit(LimitKind::Fuel), .. }))); + assert!((40..=60).contains(&slices), "{slices}"); +} + +#[test] +fn a_set_flag_stops_a_loop_in_a_getter() { + let mut r = realm(u64::MAX); + r.start("var o = {}; Object.defineProperty(o, 'x', {get: function () { while (true) {} }}); o.x").unwrap(); + r.interrupt().set(); + let e = r.advance(10).unwrap_err(); + assert_eq!(e.kind, RunErrorKind::Limit(LimitKind::Interrupted)); +} + +#[test] +fn a_nested_run_past_the_slice_allowance_is_the_unbroken_limit_and_a_run_with_little_fuel_is_the_fuel_limit() { + for (total, kind) in [(u64::MAX, LimitKind::Unbroken), (1_000, LimitKind::Fuel)] { + for source in [ + "var o = {}; Object.defineProperty(o, 'x', {get: function () { while (true) {} }}); o.x", + "[1].forEach(function () { while (true) {} });", + ] { + let mut r = realm(total); + r.set_unbroken_fuel(5_000); + r.start(source).unwrap(); + let e = finish(&mut r, 1).0.unwrap_err(); + assert_eq!(e.kind, RunErrorKind::Limit(kind), "{source}"); + } + } +} + +#[test] +fn neither_a_limit_nor_a_stop_can_be_caught() { + let mut r = realm(1_000); + r.start("try { while (true) {} } catch (e) { 'caught' } finally { 'ran' }").unwrap(); + assert_eq!(finish(&mut r, 50).0.unwrap_err().kind, RunErrorKind::Limit(LimitKind::Fuel)); + + let shared = Interrupt::new(); + let mut r = realm(1_000_000); + r.share_interrupt(&shared); + r.start("try { while (true) {} } catch (e) { 'caught' }").unwrap(); + assert_eq!(r.advance(10).unwrap(), Progress::Paused); + shared.set(); + assert_eq!(r.advance(10).unwrap_err().kind, RunErrorKind::Limit(LimitKind::Interrupted)); +} + +#[test] +fn a_host_function_can_end_the_slice() { + let mut r = realm(1_000_000); + let pause = r.pause_flag(); + let f: HostFunction = Rc::new(move |_| { + pause.set(true); + Ok(Data::Null) + }); + r.define_host_object("host", vec![("yield".into(), HostItem::Function(f))]).unwrap(); + r.start("host.yield(); host.yield(); 7").unwrap(); + assert_eq!(r.advance(1_000).unwrap(), Progress::Paused); + assert_eq!(r.advance(1_000).unwrap(), Progress::Paused); + assert_eq!(r.advance(1_000).unwrap(), Progress::Done(JsValue::Number(7.0))); +} + +#[test] +fn plain_values_cross_in_both_directions() { + let mut r = realm(1_000_000); + let seen = with_take(&mut r); + let out = r.run("var v = host.take({a: 1, b: 'x', c: [true, null], d: undefined}); v.c[0] === true && v.b === 'x' && v.d === undefined"); + assert_eq!(out.unwrap(), JsValue::Bool(true)); + let want = Data::Object(vec![ + ("a".into(), Data::Number(1.0)), + ("b".into(), Data::String("x".into())), + ("c".into(), Data::Array(vec![Data::Bool(true), Data::Null])), + ]); + assert_eq!(seen.borrow().as_slice(), [want]); +} + +#[test] +fn a_callback_of_a_built_in_can_call_the_host() { + let mut r = realm(1_000_000); + let seen = with_take(&mut r); + r.start("[1, 2, 3].forEach(function (n) { host.take(n); });").unwrap(); + finish(&mut r, 2).0.unwrap(); + assert_eq!(seen.borrow().len(), 3); +} + +/// `value` passed to the host throws an error of type `name` whose message holds `part`. +fn refused(setup: &str, name: &str, part: &str) { + let mut r = realm(10_000_000); + r.set_data_limits(DataLimits { depth: 8, bytes: 1_000, entries: 100 }); + let seen = with_take(&mut r); + let probe = format!("var e; {setup} try {{ host.take(value); }} catch (x) {{ e = x; }} e ? e.name + '|' + e.message : 'none'"); + let JsValue::String(out) = r.run(&probe).unwrap() else { panic!("{setup}") }; + assert!(out.starts_with(name) && out.contains(part), "{setup}: {out}"); + assert!(seen.borrow().is_empty(), "{setup}: the function ran"); +} + +#[test] +fn values_that_are_not_plain_data_are_refused_with_their_place() { + refused("var value = {}; value.self = value;", "TypeError", ".self refers to itself"); + refused("var value = [[1]]; value[0][0] = value;", "TypeError", "[0][0][0] refers to itself"); + refused("var value = {f: function () {}};", "TypeError", ".f is a Function"); + refused("var value = {n: 1 / 0};", "TypeError", ".n is not a finite number"); + refused("var value = {n: 0 / 0};", "TypeError", ".n is not a finite number"); + refused("var value = {d: new Date(0)};", "TypeError", ".d is a Date"); + refused("var value = {}; Object.defineProperty(value, 'g', {enumerable: true, get: function () { return 1; }});", "TypeError", ".g is a getter"); + refused("var value = [1, , 3];", "TypeError", "[0][1] is undefined"); + refused("var value = 1; for (var i = 0; i < 20; i++) value = [value];", "RangeError", "nested too deep"); + refused("var value = new Array(5000);", "RangeError", "too many entries"); + refused("var value = 'x'; for (var i = 0; i < 12; i++) value += value;", "RangeError", "too large"); +} + +#[test] +fn a_value_nested_ten_thousand_deep_is_refused_with_its_place() { + let mut r = realm(100_000_000); + let seen = with_take(&mut r); + let probe = "var v = 1; for (var i = 0; i < 10000; i++) v = {a: v}; var m = 'none'; \ + try { host.take({args: v}); } catch (e) { m = e.name + '|' + e.message; } m"; + let JsValue::String(out) = r.run(probe).unwrap() else { panic!("not a string") }; + assert!(out.starts_with("RangeError|") && out.contains(".args.a.a.a") && out.contains("nested too deep"), "{out}"); + assert!(seen.borrow().is_empty(), "the function ran"); +} + +#[test] +fn a_shared_object_is_allowed_and_sharing_cannot_multiply_the_work() { + let mut r = realm(10_000_000); + r.set_data_limits(DataLimits { depth: 64, bytes: 16 << 20, entries: 1_000 }); + let seen = with_take(&mut r); + r.run("var s = {a: 1}; host.take({x: s, y: s, z: [s, s]});").unwrap(); + assert_eq!(seen.borrow().len(), 1); + // Each level doubles the paths to the bottom: the entry limit ends the walk. + let JsValue::String(out) = + r.run("var v = [1]; for (var i = 0; i < 40; i++) v = [v, v]; var m = 'none'; try { host.take(v); } catch (e) { m = e.name; } m").unwrap() + else { + panic!() + }; + assert_eq!(out, "RangeError"); +} + +#[test] +fn a_host_object_cannot_be_changed_by_a_script() { + let mut r = realm(1_000_000); + let args = Data::Object(vec![("list".into(), Data::Array(vec![Data::Number(1.0)]))]); + r.define_host_object("vc", vec![("args".into(), HostItem::Value(args))]).unwrap(); + let out = r.run( + "vc.args.list[0] = 2; vc.args.list.push; vc.args.more = 1; vc.extra = 1; var was = vc; vc = 3; \ + [was.args.list[0], was.args.more === undefined, was.extra === undefined, Object.isFrozen(was.args.list)].join()", + ); + assert_eq!(out.unwrap(), JsValue::String("1,true,true,true".into())); +} + +#[test] +fn a_getter_is_read_each_time() { + let mut r = realm(1_000_000); + let count = Rc::new(Cell::new(0.0)); + let c = count.clone(); + let f: HostFunction = Rc::new(move |_| { + c.set(c.get() + 1.0); + Ok(Data::Number(c.get())) + }); + r.define_host_object("host", vec![("n".into(), HostItem::Getter(f))]).unwrap(); + assert_eq!(r.run("host.n + host.n").unwrap(), JsValue::Number(3.0)); +} + +#[test] +fn errors_from_the_host_can_be_caught_and_an_abort_cannot() { + let mut r = realm(1_000_000); + let f: HostFunction = Rc::new(|a| match a.first() { + Some(Data::String(k)) if k == "type" => Err(HostError::Type("bad type".into())), + Some(Data::String(k)) if k == "range" => Err(HostError::Range("bad range".into())), + Some(Data::String(k)) if k == "abort" => Err(HostError::Abort("stopped by the host".into())), + _ => Err(HostError::Error("bad".into())), + }); + r.define_host_object("host", vec![("f".into(), HostItem::Function(f))]).unwrap(); + let out = r.run( + "var a = []; ['type', 'range', 'x'].forEach(function (k) { try { host.f(k); } catch (e) { a.push(e.name + ':' + e.message); } }); a.join()", + ); + assert_eq!(out.unwrap(), JsValue::String("TypeError:bad type,RangeError:bad range,Error:bad".into())); + let e = r.run("try { host.f('abort'); } catch (e) { 'caught' }").unwrap_err(); + assert_eq!((e.kind, e.message.as_str()), (RunErrorKind::Limit(LimitKind::Host), "stopped by the host")); +} + +#[test] +fn an_error_says_where_in_the_source_it_was_raised() { + let mut r = realm(1_000_000); + r.start("var a = 1;\n throw new TypeError('no');").unwrap(); + let e = finish(&mut r, 1).0.unwrap_err(); + assert_eq!((e.kind, e.line), (RunErrorKind::Thrown, 2)); + assert!(e.column >= 3, "{}", e.column); + assert_eq!(e.message, "TypeError: no"); +} + +#[test] +fn advancing_without_a_run_is_an_error() { + let mut r = realm(1_000); + let e = r.advance(10).unwrap_err(); + assert_eq!((e.kind, e.message.as_str()), (RunErrorKind::Internal, "no run to advance")); +} + +proptest::proptest! { + /// A slice size does not change what a script computes. + #[test] + fn any_slice_size_gives_the_same_result(slice in 1u64..500, n in 0u32..300) { + let source = format!("var a = []; for (var i = 0; i < {n}; i++) a.push(i * 2); a.join().length"); + let whole = realm(50_000_000).run(&source).unwrap(); + let mut r = realm(50_000_000); + r.start(&source).unwrap(); + proptest::prop_assert_eq!(finish(&mut r, slice).0.unwrap(), whole); + } + + /// Hostile text for a value never makes the bridge panic. + #[test] + fn hostile_values_end_with_a_value_or_a_script_error(depth in 0usize..120, width in 0usize..6, cycle in proptest::bool::ANY) { + let mut r = realm(5_000_000); + with_take(&mut r); + let mut s = String::from("var v = [];"); + for _ in 0..depth { + s.push_str(&format!("v = [v{}];", ",v".repeat(width.min(2)))); + } + if cycle { + s.push_str("var c = {}; c.c = c; v = [v, c];"); + } + s.push_str("var ok = 'ok'; try { host.take(v); } catch (e) { ok = e.name; } ok"); + let JsValue::String(out) = r.run(&s).unwrap() else { panic!() }; + proptest::prop_assert!(matches!(out.as_str(), "ok" | "RangeError" | "TypeError"), "{}", out); + } +} diff --git a/crates/js/src/interp.rs b/crates/js/src/interp.rs index b110a955b4..f868149492 100644 --- a/crates/js/src/interp.rs +++ b/crates/js/src/interp.rs @@ -179,6 +179,12 @@ pub(crate) struct Interp { pub(crate) date_host: crate::date_builtins::DateHost, /// The bytes native code holds outside the heap's cells through [`HeldBytes`]. pub(crate) held: Rc, + /// Set by the host to end the current slice of a resumable run at the next safe point. + pub(crate) pause: Rc>, + /// The message of the uncatchable error a host function ended the run with. + pub(crate) host_abort: Option, + /// How much a value passed to or from a host function may carry. + pub(crate) data_limits: crate::DataLimits, } /// The bytes all live [`HeldBytes`] hold, and the bytes dropped holders released that the heap's @@ -367,6 +373,9 @@ impl Interp { install_error: None, date_host: crate::date_builtins::DateHost::default(), held: Rc::default(), + pause: Rc::default(), + host_abort: None, + data_limits: crate::DataLimits::default(), }; crate::builtins::install(&mut interp); interp.fuel = limits.fuel; @@ -558,6 +567,28 @@ impl Interp { } } + /// Runs the boundary frame on top until it returns (`Some` with its value) or the remaining + /// fuel falls to `pause_at`, or the host asks for a pause (`None`, with the frames left in + /// place for the next call). Only this outermost loop pauses: a nested run has native frames + /// under it and goes on until it returns. + pub(crate) fn execute_slice(&mut self, pause_at: u64) -> JsResult> { + loop { + match self.step() { + Ok(Some(v)) => return Ok(Some(v)), + Ok(None) => {} + Err(Abrupt::Throw(v)) => self.unwind(v)?, + Err(other) => { + self.note_site(); + self.abort_to_boundary(); + return Err(other); + } + } + if self.fuel <= pause_at || self.pause.replace(false) { + return Ok(None); + } + } + } + fn step(&mut self) -> JsResult> { self.tick()?; let frame = self.frame_mut()?; @@ -966,11 +997,11 @@ impl Interp { // ---- properties ---- - fn object(&self, id: ObjId) -> JsResult<&Object> { + pub(crate) fn object(&self, id: ObjId) -> JsResult<&Object> { self.heap.object(id).ok_or_else(|| Abrupt::Internal("object out of range".into())) } - fn object_mut(&mut self, id: ObjId) -> JsResult<&mut Object> { + pub(crate) fn object_mut(&mut self, id: ObjId) -> JsResult<&mut Object> { self.heap.object_mut(id).ok_or_else(|| Abrupt::Internal("object out of range".into())) } @@ -1815,6 +1846,11 @@ impl Interp { self.temp_roots.truncate(mark); return Ok(Prepared::Done(r?)); } + Func::Data { f, name } => { + // The arguments are read before the function runs, and a result being built + // keeps itself reachable. + return Ok(Prepared::Done(self.call_data(&f, &name, &args)?)); + } Func::Host { f: host, .. } => { let js_args: Vec = args.iter().map(|v| self.to_js_value(v)).collect(); return match host(&js_args) { @@ -2135,6 +2171,15 @@ impl Interp { if is_eval && self.reentry >= self.limits.reentry { return Err(Abrupt::Limit(LimitKind::Reentry)); } + self.enter_global(code, is_eval)?; + self.reentry += nested; + let r = self.execute(); + self.reentry -= nested; + r + } + + /// Declares `code`'s variables and functions and pushes its boundary frame, ready to run. + pub(crate) fn enter_global(&mut self, code: Rc, is_eval: bool) -> JsResult<()> { self.charge_code(&code, declaration_bytes(&code).saturating_add(ENV_BYTES))?; let (env, global) = (self.global_env, self.global); let (env, var_env) = if code.strict && is_eval { @@ -2144,11 +2189,7 @@ impl Interp { (env, env) }; self.instantiate_global(&code, var_env, is_eval)?; - self.push_code_frame(code, env, var_env, Value::Object(global), true)?; - self.reentry += nested; - let r = self.execute(); - self.reentry -= nested; - r + self.push_code_frame(code, env, var_env, Value::Object(global), true) } fn push_code_frame(&mut self, code: Rc, env: EnvId, var_env: EnvId, this: Value, boundary: bool) -> JsResult<()> { diff --git a/crates/js/src/lib.rs b/crates/js/src/lib.rs index b883be432d..a95a4b8847 100644 --- a/crates/js/src/lib.rs +++ b/crates/js/src/lib.rs @@ -47,6 +47,7 @@ mod compiler; mod date_builtins; mod error; mod heap; +mod host; mod interp; mod lexer; mod number; @@ -65,9 +66,10 @@ pub use ast::{ PropertyKey, PropertyValue, Stmt, StmtId, SwitchCase, UnaryOp, UpdateOp, VarDecl, }; pub use error::{SyntaxError, TOO_DEEP, TOO_LONG}; +pub use host::{Data, DataLimits, HostError, HostFunction, HostItem}; pub use lexer::{Goal, Lexer}; pub use number::to_string as number_to_string; -pub use realm::{Interrupt, JsValue, LimitKind, Limits, Realm, RunError, RunErrorKind}; +pub use realm::{Interrupt, JsValue, LimitKind, Limits, MAX_UNBROKEN_FUEL, Progress, Realm, RunError, RunErrorKind}; pub use token::{Directive, DirectiveName, Keyword, Punct, Span, Token, TokenKind}; /// How a script is read. @@ -185,6 +187,8 @@ impl LineTable { #[cfg(test)] mod builtins_tests; #[cfg(test)] +mod host_tests; +#[cfg(test)] mod interp_tests; #[cfg(test)] mod tests; diff --git a/crates/js/src/realm.rs b/crates/js/src/realm.rs index 45d7c08bd8..a28b150a52 100644 --- a/crates/js/src/realm.rs +++ b/crates/js/src/realm.rs @@ -51,14 +51,36 @@ pub enum LimitKind { Reentry, /// The host set the interrupt flag. Interrupted, + /// A getter, a callback of a built-in or another nested run spent [`MAX_UNBROKEN_FUEL`] + /// without returning to the point where a resumable run can pause. + Unbroken, + /// A host function ended the run ([`crate::HostError::Abort`]). + Host, +} + +/// The fuel [`Realm::advance`] lets a slice spend, past the slice it was asked for, in a nested run +/// it cannot pause. +pub const MAX_UNBROKEN_FUEL: u64 = 200_000_000; + +/// How far a resumable run got. +#[derive(Clone, Debug, PartialEq)] +pub enum Progress { + /// The slice ended; call [`Realm::advance`] again. + Paused, + /// The script ended, with its completion value. + Done(JsValue), } /// A flag the host sets, from any thread, to stop the running script at its next instruction. /// It stays set until [`Interrupt::clear`]. -#[derive(Clone, Debug)] +#[derive(Clone, Debug, Default)] pub struct Interrupt(Arc); impl Interrupt { + pub fn new() -> Self { + Self::default() + } + pub fn set(&self) { self.0.store(true, Ordering::Relaxed); } @@ -121,6 +143,7 @@ impl From for RunError { /// A global environment with the built-ins, in which scripts run one after another. pub struct Realm { interp: Interp, + unbroken_fuel: u64, } impl Default for Realm { @@ -138,7 +161,13 @@ impl Realm { /// `options`; [`Options::max_source_units`] caps the source parsed in one run, all of it /// counted together. pub fn with_options(options: Options, limits: Limits) -> Self { - Self { interp: Interp::new(options, limits) } + Self { interp: Interp::new(options, limits), unbroken_fuel: MAX_UNBROKEN_FUEL } + } + + /// Sets the fuel [`Realm::advance`] lets a nested run spend past its slice (by default + /// [`MAX_UNBROKEN_FUEL`]). + pub fn set_unbroken_fuel(&mut self, fuel: u64) { + self.unbroken_fuel = fuel; } pub fn limits(&self) -> &Limits { @@ -173,6 +202,13 @@ impl Realm { /// value of the last expression statement that ran). A realm whose built-ins could not be /// installed runs nothing and gives an internal error. pub fn run(&mut self, source: &str) -> Result { + let code = self.compile(source)?; + let result = self.interp.run_global(code, false); + self.outcome(result) + } + + /// Compiles `source` and readies the realm for a run. + fn compile(&mut self, source: &str) -> Result, RunError> { let interp = &mut self.interp; if let Some(message) = &interp.install_error { return Err(RunError { kind: RunErrorKind::Internal, message: message.clone(), line: 0, column: 0 }); @@ -181,13 +217,18 @@ impl Realm { interp.source_units = 0; interp.throw_site = None; interp.last_thrown = Value::Undefined; + interp.host_abort = None; let strict = interp.options.strict; - let code = match interp.encode_source(source).and_then(|units| interp.compile_source(&units, strict, CodeKind::Global)) { - Ok(code) => code, - Err(CompileError::Syntax(e)) => return Err(e.into()), - Err(CompileError::Internal(m)) => return Err(RunError { kind: RunErrorKind::Internal, message: m, line: 0, column: 0 }), - }; - let result = interp.run_global(code, false); + match interp.encode_source(source).and_then(|units| interp.compile_source(&units, strict, CodeKind::Global)) { + Ok(code) => Ok(code), + Err(CompileError::Syntax(e)) => Err(e.into()), + Err(CompileError::Internal(m)) => Err(RunError { kind: RunErrorKind::Internal, message: m, line: 0, column: 0 }), + } + } + + /// The end of a run: its completion value or error, with the interpreter's stacks emptied. + fn outcome(&mut self, result: Result) -> Result { + let interp = &mut self.interp; let (line, column) = interp.throw_site.take().map_or((0, 0), |(code, pc)| code.line_column(pc)); interp.stack.clear(); interp.frames.clear(); @@ -200,11 +241,84 @@ impl Realm { interp.last_thrown = v; Err(RunError { kind: RunErrorKind::Thrown, message, line, column }) } + Err(Abrupt::Limit(LimitKind::Host)) => { + let message = interp.host_abort.take().unwrap_or_else(|| format!("limit reached: {:?}", LimitKind::Host)); + Err(RunError { kind: RunErrorKind::Limit(LimitKind::Host), message, line, column }) + } Err(Abrupt::Limit(kind)) => Err(RunError { kind: RunErrorKind::Limit(kind), message: format!("limit reached: {kind:?}"), line, column }), Err(Abrupt::Internal(message)) => Err(RunError { kind: RunErrorKind::Internal, message, line, column }), } } + /// Begins a run that [`Realm::advance`] carries on: compiles `source` and enters it. + pub fn start(&mut self, source: &str) -> Result<(), RunError> { + let code = self.compile(source)?; + match self.interp.enter_global(code, false) { + Ok(()) => Ok(()), + Err(e) => self.outcome(Err(e)).map(drop), + } + } + + /// Runs the script begun with [`Realm::start`] for about `slice` units of fuel (at least one + /// instruction), and pauses where it can resume: between two instructions of the script's own + /// code. A getter, a built-in's callback or another nested run has native frames under it, so + /// it runs on to its end, for at most [`Realm::set_unbroken_fuel`] more. Once this has returned + /// [`Progress::Done`] or an error, the run is over. + pub fn advance(&mut self, slice: u64) -> Result { + let interp = &mut self.interp; + if interp.frames.is_empty() { + return Err(RunError { kind: RunErrorKind::Internal, message: "no run to advance".into(), line: 0, column: 0 }); + } + let total = interp.fuel; + let cap = slice.saturating_add(self.unbroken_fuel).min(total); + interp.fuel = cap; + let r = interp.execute_slice(cap - slice.min(cap)); + let used = cap - interp.fuel; + interp.fuel = total - used; + match r { + Ok(None) => Ok(Progress::Paused), + Ok(Some(v)) => self.outcome(Ok(v)).map(Progress::Done), + // The run's own fuel is not used up, so it was the allowance of this slice. + Err(Abrupt::Limit(LimitKind::Fuel)) if total > cap => self.outcome(Err(Abrupt::Limit(LimitKind::Unbroken))).map(Progress::Done), + Err(e) => self.outcome(Err(e)).map(Progress::Done), + } + } + + /// Is a run begun with [`Realm::start`] still going? + pub fn is_running(&self) -> bool { + !self.interp.frames.is_empty() + } + + /// The flag a host function sets to end the current slice at the next point it can pause. + pub fn pause_flag(&self) -> std::rc::Rc> { + self.interp.pause.clone() + } + + /// Has this realm stop when `interrupt` is set, in place of its own flag. + pub fn share_interrupt(&mut self, interrupt: &Interrupt) { + self.interp.interrupt = interrupt.0.clone(); + } + + /// Fuel the run has left. + pub fn fuel_left(&self) -> u64 { + self.interp.fuel + } + + /// Sets how much a value passed to or from a host function may carry. + pub fn set_data_limits(&mut self, limits: crate::DataLimits) { + self.interp.data_limits = limits; + } + + /// Adds the frozen object `name`, with `items`, to the global environment. Scripts cannot add + /// to it, change it or replace it. A heap too small for it ends with the error the realm's + /// next run would give. + pub fn define_host_object(&mut self, name: &str, items: Vec<(String, crate::HostItem)>) -> Result<(), RunError> { + match self.interp.install_host_object(name, items) { + Ok(()) => Ok(()), + Err(e) => self.outcome(Err(e)).map(drop), + } + } + /// Defines the global variable `name` holding the exception the last run did not catch /// (`undefined` if there was none). pub fn bind_last_thrown(&mut self, name: &str) { diff --git a/crates/mcp/src/server.rs b/crates/mcp/src/server.rs index b1cfd30878..a445c7146d 100644 --- a/crates/mcp/src/server.rs +++ b/crates/mcp/src/server.rs @@ -28,7 +28,8 @@ const METHOD_NOT_FOUND: i64 = -32601; const INVALID_PARAMS: i64 = -32602; const INTERNAL_ERROR: i64 = -32603; const RESOURCE_NOT_FOUND: i64 = -32002; -/// The engine is running a long call and this request was not run (implementation-defined range). +/// The engine is running a long call or a script and this request was not run +/// (implementation-defined range). pub(crate) const SERVER_BUSY: i64 = -32003; /// How long a call runs before a request that would have to wait behind it is refused as busy @@ -435,7 +436,11 @@ impl Server { if let Some(arguments) = args.as_object() { crate::tools::check_tool_arguments(name, arguments).map_err(|e| (INVALID_PARAMS, e))?; } - Ok(call_tool(self.backend.as_mut(), name, &args).to_value()) + let result = call_tool(self.backend.as_mut(), name, &args); + match result.script_busy() { + Some(message) => Err((SERVER_BUSY, message)), + None => Ok(result.to_value()), + } } "resources/read" => { let uri = params.get("uri").and_then(Value::as_str).ok_or((INVALID_PARAMS, "missing `uri`".to_string()))?; diff --git a/crates/mcp/src/tests.rs b/crates/mcp/src/tests.rs index c07aa9efce..02e5624b3e 100644 --- a/crates/mcp/src/tests.rs +++ b/crates/mcp/src/tests.rs @@ -1463,6 +1463,60 @@ fn pointer_gesture_forwards_backquote_on_each_event() { assert_eq!(rect["bounds"]["x"], 100.0, "{doc}"); } +/// The documented Rotate View calls reach the desktop control methods, preserving document +/// coordinates and modifiers, and a successful null reset remains a successful MCP response. +#[test] +fn rotate_view_calls_forward_to_desktop_control() { + use std::cell::RefCell; + use std::rc::Rc; + + struct Recording(Rc>>); + impl Backend for Recording { + fn call(&mut self, method: &str, params: Value) -> Result { + self.0.borrow_mut().push((method.into(), params)); + Ok(Value::Null) + } + fn has_ui(&self) -> bool { + true + } + fn describe(&self) -> String { + "desktop control contract".into() + } + } + + let seen = Rc::new(RefCell::new(Vec::new())); + let mut s = Server::new(Box::new(Recording(seen.clone()))); + let selected = call(&mut s, 1, "select_tool", json!({"tool": "rotateView"})); + let turned = call( + &mut s, + 2, + "pointer_gesture", + json!({"events": [ + {"kind": "down", "x": 300, "y": 150}, {"kind": "drag", "x": 200, "y": 250}, {"kind": "up", "x": 200, "y": 250} + ], "mods": {"shift": true}}), + ); + let reset = call(&mut s, 3, "command_run", json!({"id": "view.rotateReset", "params": {}})); + for reply in [&selected, &turned, &reset] { + assert_eq!(reply["isError"], false, "{reply}"); + } + assert_eq!(text_of(&reset), "null"); + assert_eq!( + *seen.borrow(), + vec![ + ("ui.tool.select".into(), json!({"tool": "rotateView"})), + ( + "ui.pointer".into(), + json!({"events": [ + {"kind": "down", "x": 300, "y": 150, "space": "doc"}, + {"kind": "drag", "x": 200, "y": 250, "space": "doc"}, + {"kind": "up", "x": 200, "y": 250, "space": "doc"} + ], "mods": {"shift": true}}) + ), + ("engine.execute".into(), json!({"command": "view.rotateReset", "params": {}})) + ] + ); +} + /// A `backquote` that is not a boolean is an error, and none of the gesture's events runs. #[test] fn pointer_gesture_rejects_a_backquote_that_is_not_a_boolean() { diff --git a/crates/mcp/src/tests/concurrency.rs b/crates/mcp/src/tests/concurrency.rs index 7b9352e526..d291d1e9fe 100644 --- a/crates/mcp/src/tests/concurrency.rs +++ b/crates/mcp/src/tests/concurrency.rs @@ -344,6 +344,23 @@ fn a_cancelled_export_through_the_real_engine_writes_nothing_and_leaves_the_sess thread.join().unwrap(); } +#[test] +fn a_change_while_a_script_runs_is_refused_as_busy() { + let mut backend = crate::Headless::with_document(); + backend.session.script_frames = true; + backend.session.execute("script.run", &json!({"source": "while (true) {}"})).unwrap(); + let mut s = Server::new(Box::new(backend)); + let call = |id: &str, params: Value| json!({"name": "command_run", "arguments": {"id": id, "params": params}}); + let reply = super::rpc(&mut s, 1, "tools/call", call("shape.rectangle", json!({"x": 0, "y": 0, "width": 1, "height": 1}))); + assert_eq!(reply["error"]["code"], -32003, "{reply}"); + assert!(reply["error"]["message"].as_str().unwrap().contains("a script is running"), "{reply}"); + let reply = super::rpc(&mut s, 2, "tools/call", json!({"name": "doc_inspect", "arguments": {}})); + assert_eq!(reply["result"]["isError"], false, "reading the document is not refused: {reply}"); + let reply = super::rpc(&mut s, 3, "tools/call", call("no.such", json!({}))); + assert_eq!(reply["result"]["isError"], true, "any other failure stays a tool error: {reply}"); + assert!(reply.get("error").is_none(), "{reply}"); +} + #[test] fn a_remote_call_stops_waiting_for_the_app_when_cancelled() { use std::io::BufRead; diff --git a/crates/mcp/src/tools.rs b/crates/mcp/src/tools.rs index 66080b6fa4..93ef5749af 100644 --- a/crates/mcp/src/tools.rs +++ b/crates/mcp/src/tools.rs @@ -36,4 +36,9 @@ impl ToolResult { pub fn to_value(&self) -> Value { json!({"content": self.content, "isError": self.is_error}) } + /// The error's text, when the engine refused the call because a script is running. + pub(crate) fn script_busy(&self) -> Option { + let text = self.content.first()?.get("text")?.as_str()?; + (self.is_error && text.ends_with(vectorcraft_engine::SCRIPT_BUSY)).then(|| text.to_string()) + } } diff --git a/crates/pdf/Cargo.toml b/crates/pdf/Cargo.toml index 66ff8b6e39..a5a3b83863 100644 --- a/crates/pdf/Cargo.toml +++ b/crates/pdf/Cargo.toml @@ -52,3 +52,9 @@ vectorcraft-text = { workspace = true, features = ["test-fonts"] } serde_json = { workspace = true } # `draw_text`, to write test files with live text as other writers do. krilla = { workspace = true, features = ["simple-text"] } + +# An independent raster oracle for gradient placement in PDF forms. These are test-only macOS +# bindings; the exporter stays portable Rust and does not depend on an OS PDF renderer. +[target.'cfg(target_os = "macos")'.dev-dependencies] +objc2-core-foundation = { version = "0.3", default-features = false, features = ["std", "CFData"] } +objc2-core-graphics = { version = "0.3", default-features = false, features = ["std", "CGBitmapContext", "CGColorSpace", "CGContext", "CGDataProvider", "CGImage", "CGPDFDocument", "CGPDFPage"] } diff --git a/crates/pdf/src/export.rs b/crates/pdf/src/export.rs index 47184d5202..c159c1f191 100644 --- a/crates/pdf/src/export.rs +++ b/crates/pdf/src/export.rs @@ -9,12 +9,11 @@ use craft_pdf::write::{self, Metadata}; use krilla::color::separation::{Color as SepColor, SeparationColorant, SeparationSpace}; use krilla::color::{cmyk, luma, rgb}; use krilla::configure::{Archival, PdfVersion}; -use krilla::geom::{Path, PathBuilder, Size, Transform}; +use krilla::geom::{Path, PathBuilder, Size}; use krilla::image::Image; use krilla::num::NormalizedF32; use krilla::page::PageSettings; use krilla::paint::{Fill, LinearGradient, RadialGradient, SpreadMethod, Stop, Stroke, StrokeDash}; -use krilla::surface::Surface; use krilla::text::{Glyph, GlyphId, KrillaGlyph}; use kurbo::{PathEl, Shape, Vec2}; use vectorcraft_color::{BlendMode, Color, GradientKind, Paint}; @@ -28,6 +27,7 @@ use crate::forms::Mark; use crate::lab_spot::{find, rfind}; use crate::marks::PageBoxes; use crate::output::ColorOut; +use crate::surface::Surface; use crate::{Compatibility, ExportReport, PdfError, PdfOptions, Standard}; mod entry; @@ -131,7 +131,7 @@ mod tests { fn writable_bounds_values_the_transform_and_values_through_it() { let mut pdf = krilla::Document::new(); let mut page = pdf.start_page_with(PageSettings::new(Size::from_wh(100.0, 100.0).unwrap())); - let mut s = page.surface(); + let mut s = Surface::page(page.surface(), 100.0); let r = Rect::new(0.0, 0.0, 10.0, 10.0); assert!(writable(&s, Affine::IDENTITY, r)); assert!(!writable(&s, Affine::IDENTITY, Rect::new(-2_147_483_649.0, 0.0, 10.0, 10.0))); diff --git a/crates/pdf/src/export/exporter.rs b/crates/pdf/src/export/exporter.rs index 2fea9a5686..d3d5f8e7fe 100644 --- a/crates/pdf/src/export/exporter.rs +++ b/crates/pdf/src/export/exporter.rs @@ -3,9 +3,11 @@ use vectorcraft_geom::Point; use super::entry::RgbInCmyk; use super::{ Affine, Arc, BezPath, BlendMode, Color, Compatibility, Document, Exporter, Fill, FillRule, HashMap, HashSet, Node, NormalizedF32, Path, - PathBuilder, PathEl, Rect, Shape, Standard, Surface, Transform, cmyk, krilla, luma, rgb, + PathBuilder, PathEl, Rect, Shape, Standard, Surface, cmyk, krilla, luma, rgb, }; +pub(super) use crate::surface::xf; + /// How deep inline graphics nest before they are left out. pub(super) const MAX_INLINE_DEPTH: u32 = 4; @@ -96,11 +98,6 @@ pub(super) const MAX_GRADIENT_PX: f64 = 4096.0; /// with overflow checks it panics on -2,147,483,648. pub(super) const MAX_COORD: f64 = 1e9; -pub(super) fn xf(a: Affine) -> Transform { - let c = a.as_coeffs(); - Transform::from_row(c[0] as f32, c[1] as f32, c[2] as f32, c[3] as f32, c[4] as f32, c[5] as f32) -} - /// The current transform of surface `s` in the content stream it draws into, without that stream's /// root transform (a page's y flip). pub(super) fn ctm(s: &Surface) -> Affine { @@ -203,9 +200,12 @@ pub(super) fn cover(s: &mut Surface, page: Rect, level: u8, opacity: f32) { /// group of that opacity that, unlike the writer's opacity groups, is not isolated. /// The cover is white, so a reader that takes every soft mask as a luminosity mask shows the same. pub(super) fn constant_mask(s: &mut Surface, page: Rect, alpha: f32) -> krilla::mask::Mask { + let transform = s.group_transform(); let mut sb = s.stream_builder(); - let mut ms = sb.surface(); + let mut ms = Surface::stream(sb.surface()); + ms.push_transform(&transform); cover(&mut ms, page, 255, alpha); + ms.pop(); ms.finish(); krilla::mask::Mask::new(sb.finish(), krilla::mask::MaskType::Alpha) } diff --git a/crates/pdf/src/export/nodes.rs b/crates/pdf/src/export/nodes.rs index dbf4b0d874..2d9a9cc175 100644 --- a/crates/pdf/src/export/nodes.rs +++ b/crates/pdf/src/export/nodes.rs @@ -22,8 +22,10 @@ impl Exporter<'_> { /// Opacity mask → luminosity soft mask. Outside the art the backdrop is black (clip) or white; /// invert is a white Difference rect on top (luminance is linear, so luma(1 − c) = 1 − luma(c)). fn soft_mask(&mut self, s: &mut Surface, m: &vectorcraft_doc::OpacityMask, page: Rect) -> Option { + let transform = s.group_transform(); let mut sb = s.stream_builder(); - let mut ms = sb.surface(); + let mut ms = Surface::stream(sb.surface()); + ms.push_transform(&transform); // An opaque backdrop when it matters: white outside the art (no clip), or black for the // inverting Difference pass below to turn white. if !m.clip || m.invert { @@ -39,6 +41,8 @@ impl Exporter<'_> { self.image_left_out = image_left_out.map(|outer| outer || incomplete); (self.knockout, self.overprint) = (knockout, overprint); if incomplete { + ms.pop(); + ms.finish(); return None; } if m.invert { @@ -46,6 +50,7 @@ impl Exporter<'_> { cover(&mut ms, page, 255, 1.0); ms.pop(); } + ms.pop(); ms.finish(); Some(krilla::mask::Mask::new(sb.finish(), krilla::mask::MaskType::Luminosity)) } @@ -96,21 +101,27 @@ impl Exporter<'_> { s.opacity = 1.0; s }; + let transform = s.group_transform(); let mut sb = s.stream_builder(); - let mut ms = sb.surface(); + let mut ms = Surface::stream(sb.surface()); + ms.push_transform(&transform); cover(&mut ms, page, 255, 1.0); let alpha = { + let transform = ms.group_transform(); let mut ab = ms.stream_builder(); - let mut als = ab.surface(); + let mut als = Surface::stream(ab.surface()); + als.push_transform(&transform); let overprint = std::mem::take(&mut self.overprint); self.measured_node(&mut als, &shape, page, false, Some(measured)); self.overprint = overprint; + als.pop(); als.finish(); krilla::mask::Mask::new(ab.finish(), krilla::mask::MaskType::Alpha) }; ms.push_mask(alpha); cover(&mut ms, page, 0, 1.0); ms.pop(); + ms.pop(); ms.finish(); krilla::mask::Mask::new(sb.finish(), krilla::mask::MaskType::Luminosity) } diff --git a/crates/pdf/src/export/paint.rs b/crates/pdf/src/export/paint.rs index 4750bef85c..9e4578bdca 100644 --- a/crates/pdf/src/export/paint.rs +++ b/crates/pdf/src/export/paint.rs @@ -351,7 +351,7 @@ impl Exporter<'_> { let cell = Rect::new(0.0, 0.0, pw, ph); let tiles = def.instances_in(Affine::IDENTITY, cell); let mut sb = s.stream_builder(); - let mut cs = sb.surface(); + let mut cs = Surface::stream(sb.surface()); let reaches_out = tiles.iter().any(|t| t.visual_bounds().is_some_and(|b| cell.intersect(b) != b)); let clip = reaches_out.then(|| to_path(&cs, &cell.to_path(0.1))).flatten(); if let Some(c) = &clip { diff --git a/crates/pdf/src/export/writer.rs b/crates/pdf/src/export/writer.rs index d7e652f2e5..027025ad2c 100644 --- a/crates/pdf/src/export/writer.rs +++ b/crates/pdf/src/export/writer.rs @@ -2,7 +2,7 @@ use super::entry::RgbInCmyk; use super::exporter::{constant_mask, cover, to_path, writable, xf}; use super::{ Affine, Arc, Archival, ColorOut, Compatibility, Document, Exporter, HashSet, Image, Metadata, Node, PageSettings, PdfError, PdfVersion, Rect, - Shape, Size, Standard, Vec2, find, krilla, rfind, write, + Shape, Size, Standard, Surface, Vec2, find, krilla, rfind, write, }; /// A PDF being written, shared by export and print: the file's configuration and metadata, then @@ -125,7 +125,7 @@ impl Writer { let size = Size::from_wh(w.max(least) as f32, h.max(least) as f32).ok_or_else(|| PdfError::BadSetting(format!("page size {w} × {h}")))?; let at = |b: Rect| krilla::geom::Rect::from_ltrb(b.x0 as f32, b.y0 as f32, b.x1 as f32, b.y1 as f32); let mut page = self.pdf.document_mut().start_page_with(PageSettings::new(size).with_trim_box(at(sheet.trim)).with_bleed_box(at(sheet.bleed))); - let mut s = page.surface(); + let mut s = Surface::page(page.surface(), size.height()); let paper = Rect::new(0.0, 0.0, w, h); if sheet.negative { cover(&mut s, paper, 255, 1.0); diff --git a/crates/pdf/src/forms.rs b/crates/pdf/src/forms.rs index 4a1d061473..b771e88b7b 100644 --- a/crates/pdf/src/forms.rs +++ b/crates/pdf/src/forms.rs @@ -13,7 +13,6 @@ use std::io::Read; use craft_pdf::write::backend as krilla; use krilla::geom::PathBuilder; use krilla::graphic::Graphic; -use krilla::surface::Surface; use std::sync::Arc; use vectorcraft_doc::{Document, Node, NodeKind}; @@ -21,6 +20,7 @@ use vectorcraft_doc::{Document, Node, NodeKind}; use crate::encrypt::{Lexer, Obj, StreamSpans, Tok, int, stream_spans}; use crate::output::{deflate, text_string}; use crate::patch::{Patch, Xref}; +use crate::surface::{Surface, affine}; use crate::{PdfError, PdfSettings, Standard}; /// What a marked form is. @@ -87,6 +87,9 @@ pub(crate) fn form(s: &mut Surface, mark: Mark, draw: impl FnOnce(&mut Surface)) /// form's drawing space), rounded outwards to whole units: [`finish`] gives the form a box that /// covers the paper and the art. pub(crate) fn layer_form(s: &mut Surface, i: usize, paper: vectorcraft_geom::Rect, draw: impl FnOnce(&mut Surface)) { + // The art and its box move into page space together; keeping the old local paper here + // would clip layers on translated artboards or give the importer a spurious clipping group. + let paper = affine(s.group_transform()).transform_rect_bbox(paper); let corner = |x: f64, y: f64| (x as f32, y as f32); marked(s, Mark::Layer(i), [corner(paper.x0.floor(), paper.y0.floor()), corner(paper.x1.ceil(), paper.y1.ceil())], draw); } @@ -94,8 +97,9 @@ pub(crate) fn layer_form(s: &mut Surface, i: usize, paper: vectorcraft_geom::Rec /// Draw `draw` as a form of its own, marked `mark`: an empty clip from the mark's first point /// through `rest`. fn marked(s: &mut Surface, mark: Mark, rest: [(f32, f32); 2], draw: impl FnOnce(&mut Surface)) { + let transform = s.group_transform(); let mut sb = s.stream_builder(); - let mut fs = sb.surface(); + let mut fs = Surface::stream(sb.surface()); let (x, y) = mark.at(); let mut pb = PathBuilder::new(); pb.move_to(x, y); @@ -108,10 +112,14 @@ fn marked(s: &mut Surface, mark: Mark, rest: [(f32, f32); 2], draw: impl FnOnce( fs.push_clip_path(&p, &krilla::paint::FillRule::NonZero); fs.pop(); } + fs.push_transform(&transform); draw(&mut fs); + fs.pop(); fs.finish(); let stream = sb.finish(); + s.push_transform(&transform.invert().unwrap_or_default()); s.draw_graphic(Graphic::new(stream, false)); + s.pop(); } // ---------- finishing the written file ---------- diff --git a/crates/pdf/src/import/builder.rs b/crates/pdf/src/import/builder.rs index b052ff7c32..61acbfc8ea 100644 --- a/crates/pdf/src/import/builder.rs +++ b/crates/pdf/src/import/builder.rs @@ -865,6 +865,9 @@ impl<'p> Builder<'p> { let vx = self.fonts.get(&key).and_then(|f| f.vertical.as_ref()).map_or(500.0, |v| v.centre(glyph)); m * kurbo::Point::new(vx, 880.0) }); + // A horizontal line is gathered in visual order and put back in logical order as a whole: + // a ligature's characters (lam-alef, lam-lam-heh) go in visual order too (#6072). + let text = if top.is_none() { visual_glyph_text(text) } else { text }; let place = |line: &mut TextLine| match top { Some(top) => line.push_upright(&look, at, opacity, Upright { top }, &text), None => line.push(&look, at, opacity, advance, &text), @@ -894,3 +897,16 @@ impl<'p> Builder<'p> { true } } + +/// The characters of one glyph in the order they are drawn: a PDF names a ligature's characters +/// in logical order (lam then alef for لا), while a horizontal line of type is gathered glyph by +/// glyph in visual order and only then put back in logical order. Right-to-left characters are +/// turned round here so that putting the line back restores them. +fn visual_glyph_text(text: String) -> String { + if text.chars().nth(1).is_none() { + return text; + } + let Some((order, _)) = vectorcraft_text::logical_order(&text) else { return text }; + let chars: Vec = text.chars().collect(); + order.iter().filter_map(|&i| chars.get(i)).collect() +} diff --git a/crates/pdf/src/lib.rs b/crates/pdf/src/lib.rs index ca7e44ae7a..5c9701e7e4 100644 --- a/crates/pdf/src/lib.rs +++ b/crates/pdf/src/lib.rs @@ -70,6 +70,7 @@ mod presets; mod print; mod settings; mod streams; +mod surface; mod syntax; pub use editing::{EDITING_FILE, Editing, LEGACY_EDITING_FILE, editing, editing_with}; diff --git a/crates/pdf/src/surface.rs b/crates/pdf/src/surface.rs new file mode 100644 index 0000000000..4229781cdd --- /dev/null +++ b/crates/pdf/src/surface.rs @@ -0,0 +1,140 @@ +//! Keep form XObjects in page space. Quartz resolves shading patterns inside a form against the +//! page's initial space, whereas other readers also apply the transform at the form's invocation. +//! Moving that transform inside the form makes both interpretations agree (including gradients +//! in opacity groups, masks, layers and overprinting art), without rasterizing the art. +//! +//! krilla's page surface has an implicit y flip which `ctm()` does not include. Remember that +//! root separately; a form's surface has an identity root. A group still counts as one push/pop +//! for the drawing code, even though moving its transform takes three krilla pushes. + +use std::ops::{Deref, DerefMut}; + +use craft_pdf::write::backend as krilla; +use krilla::blend::BlendMode; +use krilla::geom::{Path, Transform}; +use krilla::mask::Mask; +use krilla::num::NormalizedF32; +use krilla::paint::FillRule; +use vectorcraft_geom::Affine; + +pub(crate) fn xf(a: Affine) -> Transform { + let c = a.as_coeffs(); + Transform::from_row(c[0] as f32, c[1] as f32, c[2] as f32, c[3] as f32, c[4] as f32, c[5] as f32) +} + +pub(crate) fn affine(t: Transform) -> Affine { + Affine::new([t.sx(), t.ky(), t.kx(), t.sy(), t.tx(), t.ty()].map(f64::from)) +} + +struct Push { + count: usize, + root: Affine, +} + +/// A drawing surface whose form groups keep gradients and masks in the same page space. +pub(crate) struct Surface<'a> { + inner: krilla::surface::Surface<'a>, + root: Affine, + pushes: Vec, +} + +impl<'a> Surface<'a> { + /// Wrap a page while recording the writer's implicit Y flip outside its reported CTM. + pub fn page(inner: krilla::surface::Surface<'a>, height: f32) -> Self { + Self { inner, root: Affine::new([1.0, 0.0, 0.0, -1.0, 0.0, height.into()]), pushes: vec![] } + } + + /// Wrap a form or pattern stream, which starts without a page's implicit Y flip. + pub fn stream(inner: krilla::surface::Surface<'a>) -> Self { + Self { inner, root: Affine::IDENTITY, pushes: vec![] } + } + + /// Current drawing space → page space, for both a form's art and its mask. A singular + /// enclosing transform draws no area: keep that form local rather than trying to invert it. + pub fn group_transform(&self) -> Transform { + let t = xf(self.root * affine(self.inner.ctm())); + if t.invert().is_some() { t } else { Transform::identity() } + } + + /// Move the enclosing transform inside a form and record its three pushes as one group. + fn group(&mut self, push: impl FnOnce(&mut krilla::surface::Surface)) { + let t = self.group_transform(); + self.inner.push_transform(&t.invert().unwrap_or_default()); + push(&mut self.inner); + self.inner.push_transform(&t); + self.pushes.push(Push { count: 3, root: self.root }); + self.root = Affine::IDENTITY; + } + + /// Apply opacity in page space when it creates a form; full opacity is a plain push. + pub fn push_opacity(&mut self, opacity: NormalizedF32) { + if opacity == NormalizedF32::ONE { + // krilla does not create a form for full opacity. + self.inner.push_opacity(opacity); + self.plain_push(); + } else { + self.group(|s| s.push_opacity(opacity)); + } + } + + pub fn push_isolated(&mut self) { + self.group(|s| s.push_isolated()); + } + + /// The mask's stream is already in [`Self::group_transform`]'s space, like the group's art. + pub fn push_mask(&mut self, mask: Mask) { + self.group(|s| s.push_mask(mask)); + } + + fn plain_push(&mut self) { + self.pushes.push(Push { count: 1, root: self.root }); + } + + pub fn push_transform(&mut self, transform: &Transform) { + self.inner.push_transform(transform); + self.plain_push(); + } + + pub fn push_clip_path(&mut self, path: &Path, rule: &FillRule) { + self.inner.push_clip_path(path, rule); + self.plain_push(); + } + + pub fn push_blend_mode(&mut self, mode: BlendMode) { + self.inner.push_blend_mode(mode); + self.plain_push(); + } + + /// Restore the enclosing coordinate space, undoing every writer push for the last group. + /// An unmatched pop is logged rather than forwarded to the writer's stack. + pub fn pop(&mut self) { + let Some(push) = self.pushes.pop() else { + log::error!("PDF surface pop without a matching push"); + return; + }; + for _ in 0..push.count { + self.inner.pop(); + } + self.root = push.root; + } + + pub fn finish(self) { + self.inner.finish(); + } +} + +// Drawing operations use krilla directly; every push/pop above keeps our coordinate state in +// step. Stream builders are wrapped with `Surface::stream` when their surfaces are created. +impl<'a> Deref for Surface<'a> { + type Target = krilla::surface::Surface<'a>; + + fn deref(&self) -> &Self::Target { + &self.inner + } +} + +impl DerefMut for Surface<'_> { + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.inner + } +} diff --git a/crates/pdf/src/tests/live_text.rs b/crates/pdf/src/tests/live_text.rs index 4cb4417bc0..bddeb758d2 100644 --- a/crates/pdf/src/tests/live_text.rs +++ b/crates/pdf/src/tests/live_text.rs @@ -477,3 +477,43 @@ fn hebrew_comes_back_in_logical_order() { assert_eq!(shown(&t[0]), shown(&original), "{text}"); } } + +/// The text objects a PDF of `text` set in `face` imports as. +fn imported_texts(face: &vectorcraft_text::FontFace, text: &str) -> Vec { + let mut pdf = krilla::Document::new(); + let mut page = pdf.start_page_with(PageSettings::from_wh(300.0, 200.0).unwrap()); + let mut s = page.surface(); + let font = Font::new(face.file_data().to_vec().into(), face.face_index()).unwrap(); + s.draw_text(KPoint::from_xy(20.0, 50.0), font, 24.0, text, false, TextDirection::Auto); + s.finish(); + page.finish(); + let r = import_with_report(&pdf.finish().unwrap(), &ImportOptions::default()).unwrap(); + texts(&r.document).iter().map(|t| t.plain_text()).collect() +} + +#[test] +fn arabic_ligatures_keep_their_letters_in_order() { + // A lam-alef ligature is one glyph whose text is lam then alef: it must not be turned round + // with the line it sits in (#6072). + let db = vectorcraft_text::FontDb::global(); + let preferred = ["DejaVu Sans", "Arial", "Times New Roman", "Noto Sans Arabic", "Noto Naskh Arabic"].map(String::from); + // Whether `face` draws lam-alef as one glyph, the ligature the fix is about. + let ligates = |face: &vectorcraft_text::FontFace| { + let style = vectorcraft_doc::CharStyle { font_family: face.family.clone(), font_style: face.style.clone(), ..Default::default() }; + let t = TextObject::point(kurbo::Point::ORIGIN, "لا", style); + vectorcraft_text::layout(db, &t).glyphs.len() == 1 + }; + // An installed Arabic font with a lam-alef ligature whose glyphs come back as live type. + let Some(face) = preferred + .iter() + .chain(&db.families()) + .filter_map(|f| db.face(f, "Regular")) + .filter(|f| f.covers('\u{0644}') && f.covers('\u{0627}') && ligates(f)) + .find(|f| !imported_texts(f, "بب").is_empty()) + else { + return; // No such font on this host. + }; + for text in ["لا", "بلال", "السلام عليكم", "لا إله إلا الله"] { + assert_eq!(imported_texts(&face, text), [text], "in {}", face.family); + } +} diff --git a/crates/pdf/tests/gradient_forms.rs b/crates/pdf/tests/gradient_forms.rs new file mode 100644 index 0000000000..9f06c9b844 --- /dev/null +++ b/crates/pdf/tests/gradient_forms.rs @@ -0,0 +1,215 @@ +//! Gradients in forms must follow the art, including on pages with a nonzero origin. Quartz +//! exposed a failure the import/render round trip did not: it resolved a form's shading pattern +//! in page space, leaving off-centre gradients painted entirely in their last stop's colour. +//! These fixtures are original, generated geometry; no user artwork or external files are used. +#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] + +use std::sync::Arc; + +use vectorcraft_color::{BlendMode, Color, Gradient, GradientGeom, GradientKind, GradientPaint, GradientStop, Paint}; +use vectorcraft_doc::{Appearance, ColorMode, Document, Knockout, Node, OpacityMask}; +use vectorcraft_geom::{Affine, Point, Rect, shapes}; +use vectorcraft_pdf::{PdfOptions, export, import}; +use vectorcraft_testkit::raster::{assert_similar, render_artboard}; + +#[derive(Clone, Copy, Debug)] +enum Form { + Page, + Opacity, + Isolated, + Nested, + PassThrough, + Mask, + Knockout, + Layer, + Overprint, +} + +const FORMS: [Form; 9] = + [Form::Page, Form::Opacity, Form::Isolated, Form::Nested, Form::PassThrough, Form::Mask, Form::Knockout, Form::Layer, Form::Overprint]; + +fn rect(d: &mut Document, bounds: Rect, paint: Paint) -> Node { + Node::path(d.alloc_id(), shapes::rectangle(bounds), Appearance::basic(paint, Paint::None, 0.0)) +} + +fn group(d: &mut Document, n: Node) -> Node { + Node::group(d.alloc_id(), vec![Arc::new(n)]) +} + +/// Generate off-centre gradient art in each form type, moving the art and artboard together. +fn fixture(form: Form, kind: GradientKind, mode: ColorMode, origin: Point) -> (Document, PdfOptions) { + let mut d = Document::new_with_mode(120.0, 180.0, mode); + let color = |k| if mode == ColorMode::Cmyk { Color::cmyk(0.0, 0.0, 0.0, k) } else { Color::gray(k) }; + let mut gradient = GradientPaint::new(Gradient { + kind, + stops: vec![GradientStop::new(0.0, color(1.0)), GradientStop::new(0.6, color(0.4)), GradientStop::new(1.0, color(0.0))], + ..Default::default() + }); + let (start, end) = match kind { + GradientKind::Radial => (Point::new(32.0, 35.0), Point::new(60.0, 35.0)), + _ => (Point::new(10.0, 10.0), Point::new(70.0, 70.0)), + }; + gradient.geom = Some(GradientGeom { start, end, aspect: 0.8, focal: None }); + let mut n = rect(&mut d, Rect::new(10.0, 10.0, 70.0, 70.0), Paint::Gradient(Box::new(gradient))); + let mut opts = PdfOptions::default(); + match form { + Form::Page => d.page_isolate = true, + Form::Opacity => n.opacity = 0.6, + Form::Isolated => { + n = group(&mut d, n); + n.isolate = true; + } + Form::Nested => { + n.opacity = 0.75; + n = group(&mut d, n); + n.opacity = 0.8; + } + Form::PassThrough => { + n.blend = BlendMode::Multiply; + n = group(&mut d, n); + n.opacity = 0.6; + } + Form::Mask => { + let mask = rect(&mut d, Rect::new(10.0, 10.0, 44.0, 70.0), Paint::solid(Color::WHITE)); + n.extras_mut().mask = Some(Box::new(OpacityMask::new(mask, true))); + } + Form::Knockout => { + let top = rect(&mut d, Rect::new(50.0, 50.0, 80.0, 80.0), Paint::solid(Color::WHITE)); + n = Node::group(d.alloc_id(), vec![Arc::new(n), Arc::new(top)]); + n.knockout = Knockout::On; + } + Form::Layer => opts.settings.create_layers = true, + Form::Overprint => n.appearance.fill_mut().unwrap().overprint = true, + } + n.transform(Affine::translate(origin.to_vec2()), false); + d.artboards[0].rect = d.artboards[0].rect + origin.to_vec2(); + let layer = d.default_layer().unwrap(); + d.insert(Some(layer), 0, n).unwrap(); + (d, opts) +} + +/// Round trips preserve gradient placement for the form types the importer supports. +#[test] +fn gradients_in_forms_keep_their_position_when_read_back() { + // The importer has a pre-existing mismatch on the knockout's synthesized nested masks; + // Quartz below checks its actual PDF output, along with the other forms. + for form in FORMS.into_iter().filter(|f| !matches!(f, Form::Knockout)) { + for kind in [GradientKind::Linear, GradientKind::Radial] { + for origin in [Point::ORIGIN, Point::new(125.0, -80.0)] { + let (d, opts) = fixture(form, kind, ColorMode::Rgb, origin); + let back = import(&export(&d, &opts).unwrap()).unwrap(); + assert_similar(&render_artboard(&back), &render_artboard(&d), 5.0, 0.01); + } + } + } +} + +/// Layer form bounds stay page-sized after translation, without extra imported clipping groups. +#[test] +fn translated_layer_forms_cover_the_paper_in_their_new_space() { + // The layer-box repair added upstream must move with the gradient fix's form transform. + // A local-space paper box would otherwise introduce a clipping group on import. + for origin in [Point::ORIGIN, Point::new(125.0, -80.0), Point::new(-250.0, 450.0)] { + let (d, mut opts) = fixture(Form::Layer, GradientKind::Radial, ColorMode::Rgb, origin); + opts.settings.compression.compress_text = false; + let bytes = export(&d, &opts).unwrap(); + let text = String::from_utf8_lossy(&bytes); + let boxes: Vec> = text + .split("/Subtype/Form") + .skip(1) + .map(|form| { + form.split("/BBox[").nth(1).unwrap().split(']').next().unwrap().split_ascii_whitespace().map(|v| v.parse().unwrap()).collect() + }) + .collect(); + assert_eq!(boxes, [vec![0.0, 0.0, 120.0, 180.0]], "{origin:?}: the layer covers exactly the page"); + let back = import(&bytes).unwrap(); + let children = back.layers[0].children().unwrap(); + assert_eq!(children.len(), 1); + assert!(children[0].path_data().is_some(), "{origin:?}: no clipping group wraps the layer's art"); + } +} + +// Test the renderer that exhibited the fault, not just our own importer (which accepted the +// old files). OS bindings are confined to this integration-test module. +#[cfg(target_os = "macos")] +#[allow(unsafe_code)] +mod quartz { + use objc2_core_foundation::CFData; + use objc2_core_graphics::{CGBitmapContextCreate, CGColorSpace, CGContext, CGDataProvider, CGImageAlphaInfo, CGPDFDocument}; + use vectorcraft_testkit::raster::Image; + + use super::*; + + /// Render the first PDF page through Quartz as an oracle independent of our importer. + fn render(bytes: &[u8]) -> Image { + let data = CFData::from_bytes(bytes); + let provider = CGDataProvider::with_cf_data(Some(&data)).unwrap(); + let doc = CGPDFDocument::with_provider(Some(&provider)).unwrap(); + let page = CGPDFDocument::page(Some(&doc), 1).unwrap(); + let space = CGColorSpace::new_device_rgb().unwrap(); + let (width, height) = (120, 180); + let mut rgba = vec![255u8; width * height * 4]; + // SAFETY: the buffer holds every RGBA row, stays allocated and is not accessed until the + // context is dropped. All inputs are the small, generated fixtures above. + let context = unsafe { + CGBitmapContextCreate(rgba.as_mut_ptr().cast(), width, height, 8, width * 4, Some(&space), CGImageAlphaInfo::PremultipliedLast.0) + } + .unwrap(); + CGContext::draw_pdf_page(Some(&context), Some(&page)); + drop(context); + Image { width: width as u32, height: height as u32, rgba } + } + + /// Quartz places RGB and CMYK radial centres, edges and masks with their translated art. + #[test] + fn quartz_keeps_off_centre_radials_in_transparency_and_layer_forms() { + for mode in [ColorMode::Rgb, ColorMode::Cmyk] { + for form in FORMS { + for origin in [Point::ORIGIN, Point::new(125.0, -80.0)] { + let (d, opts) = fixture(form, GradientKind::Radial, mode, origin); + let img = render(&export(&d, &opts).unwrap()); + let centre = img.over_white(32, 35)[0]; + let edge = img.over_white(32, 55)[0]; + assert!(centre < 150 && edge.saturating_sub(centre) > 40, "{mode:?} {form:?} {origin:?}: centre {centre}, edge {edge}"); + assert_eq!(img.over_white(90, 100), [255; 3], "art stays in its bounds"); + if matches!(form, Form::Mask) { + assert_eq!(img.over_white(46, 35), [255; 3], "the mask moves with the gradient"); + } + } + } + } + } + + /// Quartz retains the linear ramp's direction inside forms on a translated artboard. + #[test] + fn quartz_keeps_linear_gradient_directions_in_forms() { + for form in FORMS.into_iter().filter(|f| !matches!(f, Form::Mask | Form::Knockout)) { + let (d, opts) = fixture(form, GradientKind::Linear, ColorMode::Rgb, Point::new(-30.0, 45.0)); + let img = render(&export(&d, &opts).unwrap()); + let (start, end) = (img.over_white(20, 20)[0], img.over_white(60, 60)[0]); + assert!(end.saturating_sub(start) > 60, "{form:?}: start {start}, end {end}"); + } + } + + /// A gradient's stop-opacity mask remains aligned with its colour through nested forms. + #[test] + fn quartz_keeps_gradient_stop_opacity_aligned_inside_nested_forms() { + let (mut d, opts) = fixture(Form::Nested, GradientKind::Radial, ColorMode::Rgb, Point::ORIGIN); + let mut leaves = vec![]; + d.walk(|n| { + if n.path_data().is_some() { + leaves.push(n.id); + } + }); + for id in leaves { + let fill = d.node_mut(id).unwrap().appearance.fill_mut().unwrap(); + let Paint::Gradient(g) = &mut fill.paint else { panic!("gradient fixture") }; + for stop in &mut g.gradient.stops { + stop.opacity = 0.6 * (1.0 - stop.offset); + } + } + let img = render(&export(&d, &opts).unwrap()); + let (centre, edge) = (img.over_white(32, 35)[0], img.over_white(32, 55)[0]); + assert!(centre > 145 && centre < 205 && edge > 240, "centre {centre}, edge {edge}"); + } +} diff --git a/crates/svg/src/export.rs b/crates/svg/src/export.rs index 13c4268472..eed8ecd335 100644 --- a/crates/svg/src/export.rs +++ b/crates/svg/src/export.rs @@ -98,7 +98,9 @@ fn write(doc: &Document, opts: &ExportOptions, native: Option<&[u8]>, id_prefix: brushes: None, knockout: doc.page_knockout, anonymous: false, - knockout_filter: None, + knockout_filters: HashMap::new(), + region_boxes: None, + art_reach: HashMap::new(), warnings: vec![], id_prefix, linked: Vec::new(), @@ -255,8 +257,13 @@ struct Writer<'a> { knockout: bool, /// Writing a copy of an object (a knockout mask): no object ids, so they stay unique. anonymous: bool, - /// The filter that paints art black keeping its alpha (knockout masks), once defined. - knockout_filter: Option, + /// The filters that paint art black keeping its alpha (knockout masks), by the region + /// attributes they were defined with. + knockout_filters: HashMap, + /// The document's symbol boxes, measured once for every mask and filter region. + region_boxes: Option>, + /// How far each symbol's art paints past its box, by name, once measured for a region. + art_reach: HashMap, /// The brush library, parsed when the first brushed stroke is written. brushes: Option>, /// Features written approximately (once each). diff --git a/crates/svg/src/export/nodes.rs b/crates/svg/src/export/nodes.rs index adcd3fd259..129bd83e28 100644 --- a/crates/svg/src/export/nodes.rs +++ b/crates/svg/src/export/nodes.rs @@ -2,8 +2,8 @@ use super::output::{sanitize_id, valid_xml_value, xml_attr_escape, xml_attr_vali use super::paint::{StrokePlan, has_raster, pixel_gradient}; use super::text::OUTLINE_TOLERANCE; use super::{ - Affine, AppearanceItem, BezPath, BlendMode, Document, FillRule, Node, NodeKind, Paint, PathData, Props, Rect, StrokeAlign, StrokeLayer, Writer, - Written, WrittenShape, blend_css, css, fmt_num, stroke, xml_escape, + Affine, AppearanceItem, BezPath, BlendMode, Document, FillRule, HashMap, Node, NodeKind, Paint, PathData, Props, Rect, StrokeAlign, StrokeLayer, + Writer, Written, WrittenShape, blend_css, css, fmt_num, stroke, xml_escape, }; /// A symbol's `` def and the instance transforms that can `` it. @@ -143,9 +143,12 @@ fn pin_to_page(n: &mut Node, m: Affine) { const TINY_MASKS: &str = "SVG Tiny 1.2 has no masks: opacity masks are left out and knockout groups written as plain groups"; pub(super) const UNDECODED: &str = "an image couldn't be decoded and is missing from the picture"; -/// A region covering any artwork (mask and filter extents). +/// The region of a mask or filter over art that has no box to measure: one covering any artwork. const BIG: &str = "x=\"-100000\" y=\"-100000\" width=\"200000\" height=\"200000\""; +/// How deep [`Writer::paint_reach`] looks into members and symbol art. +const MAX_REACH_DEPTH: u32 = 64; + /// Attributes of every ``: user-space units, and luminance taken from the sRGB values (as the /// canvas and PDF take it) rather than from linearised ones. pub(super) const MASK: &str = "maskUnits=\"userSpaceOnUse\" color-interpolation=\"sRGB\""; @@ -354,13 +357,18 @@ impl Writer<'_> { return self.node_body(&bare); } let mid = self.fresh_id("mask"); + let mut bare = n.clone(); + bare.extras_mut().mask = None; + // The region covers what the object and the mask art paint: readers draw the mask into an + // image of the region's size. + let region = self.region_attrs(&[&bare, &m.art]); // Mask art is a picture of its own: it takes no part in a knockout group around the object. let knockout = std::mem::take(&mut self.knockout); let art = self.detached(2, |w| w.node(&m.art)); self.knockout = knockout; let inv = m.invert.then(|| { let fid = self.fresh_id("invert"); - self.def(1, &format!("")); + self.def(1, &format!("")); self.def(2, ""); self.def(1, ""); fid @@ -368,13 +376,13 @@ impl Writer<'_> { // The mask's options, so import restores them (and its art without backdrop and filter). let flags: Vec<&str> = [(!m.clip).then_some("noclip"), m.invert.then_some("invert")].into_iter().flatten().collect(); let data = if flags.is_empty() { String::new() } else { format!(" {MASK_FLAGS}=\"{}\"", flags.join(" ")) }; - self.def(1, &format!("")); + self.def(1, &format!("")); if let Some(fid) = &inv { self.def(1, &format!("")); } if !m.clip || m.invert { let c = if m.clip { "black" } else { "white" }; - self.def(1, &format!("")); + self.def(1, &format!("")); } self.defs.push_str(&art); if inv.is_some() { @@ -383,8 +391,6 @@ impl Writer<'_> { self.def(1, ""); self.line(&format!("")); self.depth += 1; - let mut bare = n.clone(); - bare.extras_mut().mask = None; self.node_body(&bare); self.depth -= 1; self.line(""); @@ -399,6 +405,127 @@ impl Writer<'_> { std::mem::replace(&mut self.body, body) } + /// The `x`, `y`, `width` and `height` of a mask or filter region over `nodes`, in the current + /// user space: the box of everything they paint ([`Self::paint_reach`]), 2 larger on each + /// side for antialiasing. [`BIG`] when none of them has a box, when one holds type (a reader + /// sets live type in its own font, which can be wider, and type on a path is measured by its + /// path), or when one nests deeper than [`MAX_REACH_DEPTH`]. The art of a symbol instance + /// written in place keeps its strokes and effects at their own size while the instance scales + /// its geometry, so the region also covers the geometry's box, placed, grown by the strokes' + /// and effects' reach unscaled. + fn region_attrs(&mut self, nodes: &[&Node]) -> String { + let symbols = self.region_boxes.take().unwrap_or_else(|| self.doc.symbol_boxes()); + let mut art_reach = std::mem::take(&mut self.art_reach); + let region = self.region_of(&symbols, &mut art_reach, nodes); + self.region_boxes = Some(symbols); + self.art_reach = art_reach; + region + } + + /// [`Self::region_attrs`] with the document's symbol boxes and the symbols' art reach so far. + fn region_of(&self, symbols: &vectorcraft_doc::SymbolBoxes, art_reach: &mut HashMap, nodes: &[&Node]) -> String { + let mut painted: Option = None; + for n in nodes { + let Some(v) = n.visual_bounds_with(symbols) else { continue }; + let Some(r) = self.paint_reach(symbols, art_reach, n, v, 0) else { + return BIG.to_string(); + }; + let g = n.geometric_bounds_with(symbols).unwrap_or(v); + let stroke = [g.x0 - v.x0, g.y0 - v.y0, v.x1 - g.x1, v.y1 - g.y1].into_iter().fold(0.0, f64::max); + let scaled = self.xf.transform_rect_bbox(v.inflate(r, r)); + let unscaled = self.xf.transform_rect_bbox(g).inflate(stroke + r, stroke + r); + let both = scaled.union(unscaled); + painted = Some(painted.map_or(both, |p| p.union(both))); + } + let Some(b) = painted.map(|b| b.inflate(2.0, 2.0)).filter(|b| b.is_finite()) else { + return BIG.to_string(); + }; + format!("x=\"{}\" y=\"{}\" width=\"{}\" height=\"{}\"", self.num(b.x0), self.num(b.y0), self.num(b.width()), self.num(b.height())) + } + + /// How far what `n` paints reaches past its visual box `b`: the reach of its own raster effects + /// and of those of its fills and strokes (measured as [`Self::open_filters`] measures them), + /// how far brush art can paint past its brushed strokes (`16 × w + 8` for the widest brushed + /// stroke `w`, as the canvas allows for it), and the most that one of its members or its + /// symbol's art reaches past its own box, spread by its own effects. `art_reach` keeps each + /// symbol's art reach by name once measured, so art used many times is measured once. A live + /// object is measured as the art it is written as: expanded on its own, as [`Self::node`] + /// expands it, so with the same limits. `None` when `n`, its members or its symbol's art hold + /// type, or nest deeper than [`MAX_REACH_DEPTH`]. + fn paint_reach( + &self, + symbols: &vectorcraft_doc::SymbolBoxes, + art_reach: &mut HashMap, + n: &Node, + b: Rect, + depth: u32, + ) -> Option { + use vectorcraft_effects::RasterFx; + // Type draws past its measured box in a reader's own font. + if matches!(n.kind, NodeKind::Text(_)) { + return None; + } + // An Outer Glow's silhouette grows by a quarter of a pixel of the document's raster grid first. + let grow = 18.0 / self.doc.raster_ppi(); + let reach = |effects: &[vectorcraft_doc::Effect]| -> f64 { + vectorcraft_effects::raster_effects(effects) + .iter() + .map(|f| f.outset(b) + if matches!(f, RasterFx::OuterGlow { .. }) { grow } else { 0.0 }) + .sum() + }; + let items = n.appearance.items.iter().map(|i| reach(i.effects())).fold(0.0, f64::max); + let brush = if vectorcraft_brush::has_brush(n) { + let w = + n.appearance.items.iter().filter_map(|i| if let AppearanceItem::Stroke(s) = i { Some(s.width) } else { None }).fold(1.0, f64::max); + 16.0 * w + 8.0 + } else { + 0.0 + }; + let own = reach(&n.appearance.effects) + items + brush; + if vectorcraft_doc::live::is_live(n) { + if depth >= MAX_REACH_DEPTH { + return None; + } + let g = vectorcraft_effects::expand_live_deep(Some(self.doc), n); + let Some(gb) = g.visual_bounds_with(symbols) else { return Some(own) }; + let past = [b.x0 - gb.x0, b.y0 - gb.y0, gb.x1 - b.x1, gb.y1 - b.y1].into_iter().fold(0.0, f64::max); + return Some(own + past + self.paint_reach(symbols, art_reach, &g, gb, depth + 1)?); + } + let symbol = match &n.kind { + NodeKind::SymbolInstance { symbol, xf } => self.doc.symbols.iter().find(|s| s.name == *symbol).map(|s| (s, xf)), + _ => None, + }; + if n.children().is_none_or(|c| c.is_empty()) && symbol.is_none() { + return Some(own); + } + if depth >= MAX_REACH_DEPTH { + return None; + } + let mut inner: f64 = 0.0; + for c in n.children().into_iter().flatten() { + if let Some(cb) = c.visual_bounds_with(symbols) { + inner = inner.max(self.paint_reach(symbols, art_reach, c, cb, depth + 1)?); + } + } + if let Some((s, xf)) = symbol { + let art = match art_reach.get(&s.name) { + Some(r) => *r, + None => { + let r = match s.art.visual_bounds_with(symbols) { + Some(ab) => self.paint_reach(symbols, art_reach, &s.art, ab, depth + 1)?, + None => 0.0, + }; + art_reach.insert(s.name.clone(), r); + r + } + }; + // The art's reach, measured in symbol space, as far as the instance can stretch it. + let [xx, xy, yx, yy, _, _] = xf.as_coeffs(); + inner = inner.max(art * xx.hypot(xy).max(yx.hypot(yy)).max(1.0)); + } + Some(own + inner) + } + /// Props of a group (or layer): a knockout group is isolated, a hidden one not displayed. fn group_props(&self, n: &Node) -> Props { let mut p = css::transparency(n); @@ -450,9 +577,12 @@ impl Writer<'_> { written.push((before, self.detached(depth + nest - 1 - i, |w| w.node(c)))); } let after = self.symbol_nodes; + // Each mask covers what the group's elements paint. + let all: Vec<&Node> = elements.iter().map(|c| &***c).collect(); + let region = self.region_attrs(&all); for (c, (before, _)) in rest.iter().zip(&written).rev() { self.symbol_nodes = *before; - let mid = self.knockout_mask(c); + let mid = self.knockout_mask(c, ®ion); self.line(&format!("")); self.depth += 1; } @@ -466,16 +596,18 @@ impl Writer<'_> { } /// A mask that is 1 − the knockout shape of `c`: white, then `c` painted black (at full object - /// opacity without its own mask, unless those define its shape). Returns the mask id. - fn knockout_mask(&mut self, c: &Node) -> String { - let filter = match &self.knockout_filter { + /// opacity without its own mask, unless those define its shape). `region` is the attributes of + /// the mask's region ([`Self::region_attrs`]), which the filter that paints `c` black shares. + /// Returns the mask id. + fn knockout_mask(&mut self, c: &Node, region: &str) -> String { + let filter = match self.knockout_filters.get(region) { Some(f) => f.clone(), None => { let f = self.fresh_id("knockout-shape"); - self.def(1, &format!("")); + self.def(1, &format!("")); self.def(2, ""); self.def(1, ""); - self.knockout_filter = Some(f.clone()); + self.knockout_filters.insert(region.to_string(), f.clone()); f } }; @@ -490,8 +622,8 @@ impl Writer<'_> { let art = self.detached(3, |w| w.node(&shape)); self.anonymous = anonymous; let mid = self.fresh_id("knockout"); - self.def(1, &format!("")); - self.def(2, &format!("")); + self.def(1, &format!("")); + self.def(2, &format!("")); self.def(2, &format!("")); self.defs.push_str(&art); self.def(2, ""); diff --git a/crates/svg/tests/it/blend_export.rs b/crates/svg/tests/it/blend_export.rs index 65fb26799c..3804d30ed2 100644 --- a/crates/svg/tests/it/blend_export.rs +++ b/crates/svg/tests/it/blend_export.rs @@ -1,10 +1,11 @@ //! Blend modes and opacity masks in SVG export look as on the canvas: every mode follows the //! reference formulas when resvg draws the file, and masks take luminance the canvas's way. +use usvg::roxmltree; use vectorcraft_color::blend::blend_rgb; use vectorcraft_color::{BlendMode, Color, Paint}; -use vectorcraft_doc::{Appearance, Document, Node, OpacityMask}; -use vectorcraft_geom::{Rect, shapes}; +use vectorcraft_doc::{Appearance, CharStyle, Document, Node, NodeKind, OpacityMask, TextObject}; +use vectorcraft_geom::{Point, Rect, shapes}; use vectorcraft_svg::{ExportOptions, export}; use vectorcraft_testkit::raster::{Image, render_artboard}; @@ -138,3 +139,126 @@ fn a_knockout_group_with_a_brushed_stroke_keeps_its_masks() { let svg = export(&d, &ExportOptions::default()); assert!(svg.contains("` and `` element in `svg`. +fn regions(svg: &str) -> Vec<[f64; 4]> { + let xml = roxmltree::Document::parse_with_options(svg, roxmltree::ParsingOptions { allow_dtd: true, ..Default::default() }).unwrap(); + xml.descendants() + .filter(|n| matches!(n.tag_name().name(), "mask" | "filter")) + .map(|n| ["x", "y", "width", "height"].map(|a| n.attribute(a).and_then(|v| v.parse().ok()).unwrap_or(f64::NAN))) + .collect() +} + +/// Mask and filter regions cover the art they apply to and no more: readers draw a mask into an +/// image of its region's size, and one drawn at 200,000 units square runs out of memory. +#[test] +fn mask_and_filter_regions_cover_their_art() { + let knockout = { + let mut d = Document::new(40.0, 20.0); + let below = rect(&mut d, Rect::new(0.0, 0.0, 40.0, 20.0), [200, 0, 0]); + let mut top = rect(&mut d, Rect::new(5.0, 5.0, 15.0, 15.0), [0, 0, 200]); + top.opacity = 0.5; + let mut group = Node::group(d.alloc_id(), vec![below.into(), top.into()]); + group.knockout = vectorcraft_doc::Knockout::On; + add(&mut d, group); + d + }; + for (what, d) in [("clip", masked(true, false)), ("no clip, inverted", masked(false, true)), ("knockout", knockout)] { + let svg = export(&d, &ExportOptions::default()); + let found = regions(&svg); + assert!(!found.is_empty(), "{what}: {svg}"); + for [x, y, w, h] in found { + // The art is 40 × 20, with 2 to spare on each side. + assert!(x >= -2.5 && y >= -2.5 && w <= 45.0 && h <= 25.0 && w >= 40.0 && h >= 20.0, "{what}: {x} {y} {w} {h} in {svg}"); + } + } +} + +/// A mask's region reaches as far as the masked art paints: a drop shadow of the object, or of an +/// object in the masked group, shows past the object as on the canvas. +#[test] +fn a_mask_region_keeps_the_shadows_of_the_masked_art() { + let shadow = vectorcraft_doc::Effect { + id: "stylize.dropShadow".into(), + params: serde_json::json!({"x": 15, "y": 15, "blur": 0, "opacity": 100}), + visible: true, + }; + for in_group in [false, true] { + let mut d = Document::new(60.0, 60.0); + let mut red = rect(&mut d, Rect::new(10.0, 10.0, 30.0, 30.0), [255, 0, 0]); + red.appearance.effects.push(shadow.clone()); + let mut masked = if in_group { Node::group(d.alloc_id(), vec![red.into()]) } else { red }; + // An unclipped mask lets the art show outside the mask art: all of the shadow shows. + let art = rect(&mut d, Rect::new(10.0, 10.0, 20.0, 30.0), [255, 255, 255]); + masked.extras_mut().mask = Some(Box::new(OpacityMask::new(art, false))); + add(&mut d, masked); + let svg = export(&d, &ExportOptions::default()); + let (canvas, written) = (render_artboard(&d), resvg_render(&svg, 60, 60)); + for (x, y) in [(15, 15), (40, 40), (35, 28)] { + let (c, w) = (canvas.over_white(x, y), written.over_white(x, y)); + assert!(within(c, w, 3), "in a group {in_group}, at {x},{y}: canvas {c:?}, svg {w:?}\n{svg}"); + } + assert!(canvas.over_white(40, 40)[0] < 100, "the shadow shows on the canvas: {:?}", canvas.over_white(40, 40)); + } +} + +/// Type is measured by its layout or its path, and a reader sets live type in its own font, so a +/// mask or knockout over type keeps the region that covers any artwork. +#[test] +fn mask_and_filter_regions_over_type_cover_any_artwork() { + let style = CharStyle { size: 24.0, fill: Paint::solid(Color::BLACK), ..CharStyle::default() }; + let text = |d: &mut Document| Node::new(d.alloc_id(), NodeKind::Text(Box::new(TextObject::point(Point::new(5.0, 30.0), "Wide", style.clone())))); + let masked = { + let mut d = Document::new(80.0, 40.0); + let mut t = text(&mut d); + let art = rect(&mut d, Rect::new(0.0, 0.0, 40.0, 40.0), [255, 255, 255]); + t.extras_mut().mask = Some(Box::new(OpacityMask::new(art, false))); + add(&mut d, t); + d + }; + let knockout = { + let mut d = Document::new(80.0, 40.0); + let below = rect(&mut d, Rect::new(0.0, 0.0, 80.0, 40.0), [200, 0, 0]); + let mut top = text(&mut d); + top.opacity = 0.5; + let mut group = Node::group(d.alloc_id(), vec![below.into(), top.into()]); + group.knockout = vectorcraft_doc::Knockout::On; + add(&mut d, group); + d + }; + for (what, d) in [("masked type", masked), ("type in a knockout group", knockout)] { + let svg = export(&d, &ExportOptions::default()); + let found = regions(&svg); + assert!(!found.is_empty(), "{what}: {svg}"); + for [x, y, w, h] in found { + assert!(x <= -100000.0 && y <= -100000.0 && w >= 200000.0 && h >= 200000.0, "{what}: {x} {y} {w} {h} in {svg}"); + } + } +} + +/// A live object under a mask is measured as it is written, expanded: the mask's region covers +/// the drop shadows of a blend's steps. +#[test] +fn a_mask_region_covers_a_blend_as_written() { + let shadow = vectorcraft_doc::Effect { + id: "stylize.dropShadow".into(), + params: serde_json::json!({"x": 15, "y": 15, "blur": 0, "opacity": 100}), + visible: true, + }; + let mut d = Document::new(100.0, 50.0); + let mut a = rect(&mut d, Rect::new(10.0, 10.0, 20.0, 20.0), [255, 0, 0]); + let mut b = rect(&mut d, Rect::new(70.0, 10.0, 80.0, 20.0), [0, 0, 255]); + a.appearance.effects.push(shadow.clone()); + b.appearance.effects.push(shadow); + let mut blend = Node::new(d.alloc_id(), NodeKind::Blend { children: vec![a.into(), b.into()], spec: Default::default() }); + let art = rect(&mut d, Rect::new(0.0, 0.0, 5.0, 5.0), [255, 255, 255]); + blend.extras_mut().mask = Some(Box::new(OpacityMask::new(art, false))); + add(&mut d, blend); + let svg = export(&d, &ExportOptions::default()); + // The steps' drop shadows are filters with regions of their own; the mask's covers them all: + // the steps run from 10 to 80 across, and their shadows 15 further. + let xml = roxmltree::Document::parse_with_options(&svg, roxmltree::ParsingOptions { allow_dtd: true, ..Default::default() }).unwrap(); + let mask = xml.descendants().find(|n| n.has_tag_name("mask")).unwrap(); + let [x, y, w, h] = ["x", "y", "width", "height"].map(|a| mask.attribute(a).and_then(|v| v.parse::().ok()).unwrap_or(f64::NAN)); + assert!(x <= 0.0 && y <= 0.0 && x + w >= 95.0 && y + h >= 35.0 && w < 200.0 && h < 200.0, "{x} {y} {w} {h} in {svg}"); +} diff --git a/crates/svg/tests/it/import_details.rs b/crates/svg/tests/it/import_details.rs index 57a7251bdc..10418f3441 100644 --- a/crates/svg/tests/it/import_details.rs +++ b/crates/svg/tests/it/import_details.rs @@ -645,3 +645,26 @@ fn nested_svg_images_past_count_cap_are_left_out() { let (_d, warnings) = import_with(&svg, &ImportOptions::default()).unwrap(); assert!(warnings.iter().any(|w| w.contains(&format!("more than {MAX_NESTED_SVG_IMAGES} nested SVG images")))); } + +/// #3566: entity references in element content count toward the expansion limit, as in +/// attributes. A 10 KB entity, a second entity that refers to it 250 times, and eight references +/// to the second inside `` would expand to about 20 MB from a file of a few KB: the import +/// refuses it before the XML reader expands anything. The namespace entities drawing apps write +/// (`&ns_svg;`) still import. +#[test] +fn entities_repeated_in_element_content_are_refused_and_namespace_entities_import() { + let bomb = format!( + r#"]>{}"#, + "x".repeat(10_000), + "&a;".repeat(250), + "&b;".repeat(8) + ); + assert!(bomb.len() < 20_000, "{} bytes", bomb.len()); + match import_with(&bomb, &ImportOptions::default()) { + Err(SvgError::Parse(e)) => assert!(e.contains("entities"), "{e}"), + other => panic!("refused as a parse error, not {:?}", other.map(|(_, w)| w)), + } + let ns = r#"]>"#; + let (d, _) = import_with(ns, &ImportOptions::default()).unwrap(); + assert_eq!(art(&d).len(), 1, "the rectangle"); +} diff --git a/crates/svg/tests/it/mask_options.rs b/crates/svg/tests/it/mask_options.rs index 541a8f702c..16c021391e 100644 --- a/crates/svg/tests/it/mask_options.rs +++ b/crates/svg/tests/it/mask_options.rs @@ -55,6 +55,27 @@ fn an_inverted_unclipped_mask_round_trips() { } } +/// Mask art that reaches past the masked object comes back whole: the mask's region covers the art +/// as well as the object, so import does not clip the art to the region. +#[test] +fn mask_art_larger_than_its_object_round_trips_unclipped() { + let mut d = Document::new(200.0, 200.0); + let red = Appearance::basic(Paint::solid(Color::rgb(1.0, 0.0, 0.0)), Paint::None, 0.0); + let white = Appearance::basic(Paint::solid(Color::WHITE), Paint::None, 0.0); + let mut n = Node::path(d.alloc_id(), shapes::rectangle(Rect::new(50.0, 50.0, 100.0, 100.0)), red); + let art = Node::path(d.alloc_id(), shapes::rectangle(Rect::new(10.0, 20.0, 180.0, 170.0)), white); + n.extras_mut().mask = Some(Box::new(OpacityMask::new(art, false))); + let l = d.layers[0].id; + d.insert(Some(l), 0, n).unwrap(); + let s = export(&d, &ExportOptions::default()); + let (back, warnings) = import_with_report(&s).unwrap(); + assert!(warnings.is_empty(), "{warnings:?}"); + let [m] = &masks(&back)[..] else { panic!("one masked object: {s}") }; + assert!(m.art.path_data().is_some(), "the art alone, not clipped by the region: {:?}\n{s}", m.art.kind); + let b = m.art.geometric_bounds().unwrap(); + assert!((b.x0 - 10.0).abs() < 1e-6 && (b.y0 - 20.0).abs() < 1e-6 && (b.x1 - 180.0).abs() < 1e-6 && (b.y1 - 170.0).abs() < 1e-6, "{b:?}"); +} + #[test] fn foreign_masks_keep_their_art() { // Without the attribute a white backdrop is part of the mask art (another app's file). diff --git a/crates/svg/tests/it/symbols_layers.rs b/crates/svg/tests/it/symbols_layers.rs index 0fad6ff096..3e58b02286 100644 --- a/crates/svg/tests/it/symbols_layers.rs +++ b/crates/svg/tests/it/symbols_layers.rs @@ -296,6 +296,31 @@ fn masks_in_symbols_move_with_the_art_when_linked() { } } +/// A masked object in a symbol's art, drawn by an instance that scales it down: its stroke keeps +/// its weight, and the mask's region still covers all of it. +#[test] +fn a_mask_in_a_scaled_instance_covers_the_strokes_at_their_weight() { + let mut d = Document::new(120.0, 120.0); + let stroked = Appearance::basic(Paint::solid(Color::rgb8(200, 0, 0)), Paint::solid(Color::BLACK), 20.0); + let mut art = Node::path(d.alloc_id(), shapes::rectangle(Rect::new(0.0, 0.0, 100.0, 100.0)), stroked); + let shape = Node::path( + d.alloc_id(), + shapes::rectangle(Rect::new(0.0, 0.0, 50.0, 100.0)), + Appearance::basic(Paint::solid(Color::WHITE), Paint::None, 0.0), + ); + art.extras_mut().mask = Some(Box::new(vectorcraft_doc::OpacityMask::new(shape, false))); + d.symbols.push(Symbol { dynamic: false, name: "Framed".into(), art: Arc::new(art) }); + instance(&mut d, "Framed", Affine::translate((50.0, 50.0)) * Affine::scale(0.2)); + let svg = export(&d, &ExportOptions::default()); + let (canvas, written) = (render_artboard(&d), resvg_render(&svg, 120, 120)); + // The stroke runs 10 either side of the 20 × 20 square's edge at (50, 50). + for (x, y) in [(43, 60), (77, 60), (60, 43), (60, 77)] { + let (c, w) = (canvas.over_white(x, y), written.over_white(x, y)); + assert!(c.iter().all(|v| *v < 60), "the stroke shows on the canvas at {x},{y}: {c:?}"); + assert!(c.iter().zip(w).all(|(a, b)| (*a as i32 - b as i32).abs() <= 8), "at {x},{y}: canvas {c:?}, svg {w:?}\n{svg}"); + } +} + #[test] fn symbols_inside_themselves_end() { let mut d = symbol_doc(1.0, &[Affine::translate((50.0, 50.0))]); diff --git a/crates/text/src/tests/harakat.rs b/crates/text/src/tests/harakat.rs index c097fc48b9..e590f103c7 100644 --- a/crates/text/src/tests/harakat.rs +++ b/crates/text/src/tests/harakat.rs @@ -512,6 +512,43 @@ fn assert_authored_ownership(t: &TextObject, text: &str, l: &TextLayout, what: & } } +/// Repeated glyphs in one cluster can belong to differently painted runs. Match each authored +/// occurrence in order, without needing an installed font, and still reject a changed owner. +#[test] +fn duplicate_authored_glyphs_keep_occurrence_order() { + let mut text = TextObject::point(Point::ZERO, "\u{0651}", style(FAMILY)); + text.runs.push(vectorcraft_doc::TextRun::new("\u{0651}", CharStyle { fill: red(), ..style(FAMILY) })); + let glyph = |run| PositionedGlyph { + outline: Default::default(), + run, + byte: 0, + origin: Point::ZERO, + advance: 0.0, + len: 4, + angle: 0.0, + line: 0, + font_id: 0, + gid: 7, + xf: Affine::IDENTITY, + rtl: true, + scale: 1.0, + image: None, + colour: None, + bend: None, + unturned: Affine::IDENTITY, + pivot: Point::ZERO, + carets: Vec::new(), + width: 0.0, + width_start: 0.0, + }; + let before = TextLayout { glyphs: vec![glyph(0), glyph(1)], ..TextLayout::default() }; + assert_eq!(assert_kashida_ownership(&text, &before, &before, &red(), "duplicate glyphs", false), 0); + + let mut wrong = before.clone(); + wrong.glyphs[0].run = 1; + assert!(std::panic::catch_unwind(|| assert_kashida_ownership(&text, &before, &wrong, &red(), "changed owner", false)).is_err()); +} + /// Compare authored glyph run indices before/after Insert Kashidas (matched by byte and gid; /// layout order can differ between point and justified area), and assert every inserted tatweel /// uses the base letter's paint at the cluster start—not `mark_fill`. When `require_mark_last`, @@ -525,16 +562,17 @@ fn assert_kashida_ownership( what: &str, require_mark_last: bool, ) -> usize { - let mut before_runs: std::collections::HashMap<(usize, u32), Vec> = std::collections::HashMap::new(); + let mut before_runs: std::collections::HashMap<(usize, u32), std::collections::VecDeque> = std::collections::HashMap::new(); for g in before.glyphs.iter().filter(|g| g.len > 0) { - before_runs.entry((g.byte, g.gid)).or_default().push(g.run); + before_runs.entry((g.byte, g.gid)).or_default().push_back(g.run); } let mut after_n = 0; for g in with_kashida.glyphs.iter().filter(|g| g.len > 0) { after_n += 1; let runs = before_runs.get_mut(&(g.byte, g.gid)).unwrap_or_else(|| panic!("{what}: authored glyph {} at {} missing before kashida", g.gid, g.byte)); - let want_run = runs.pop().unwrap_or_else(|| panic!("{what}: no remaining before-run for {} at {}", g.gid, g.byte)); + // Duplicate glyphs at the same cluster byte retain their occurrence order. + let want_run = runs.pop_front().unwrap_or_else(|| panic!("{what}: no remaining before-run for {} at {}", g.gid, g.byte)); assert_eq!(g.run, want_run, "{what}: authored run at {} gid {}", g.byte, g.gid); let want_fill = coloured.runs.get(want_run).map(|r| &r.style.fill).unwrap_or_else(|| panic!("{what}: missing run {want_run}")); assert_eq!(&run_of(coloured, g).style.fill, want_fill, "{what}: authored fill at {}", g.byte); diff --git a/crates/tools/src/addons/smart_pen.rs b/crates/tools/src/addons/smart_pen.rs index 90c73620a1..4ee448830d 100644 --- a/crates/tools/src/addons/smart_pen.rs +++ b/crates/tools/src/addons/smart_pen.rs @@ -547,6 +547,11 @@ impl Tool for SmartPenTool { key == ToolKey::Tab && (self.press.is_some() || self.active(cx).is_some()) } + /// A path being drawn: Escape ends it. + fn ends_on_escape(&self, _cx: &ToolContext) -> bool { + self.path.is_some() + } + fn deactivate(&mut self, _cx: &ToolContext) -> Vec { self.stop(); self.marquee = None; diff --git a/crates/tools/src/dimension.rs b/crates/tools/src/dimension.rs index 44bbbf44b2..53fbd3f3f5 100644 --- a/crates/tools/src/dimension.rs +++ b/crates/tools/src/dimension.rs @@ -67,8 +67,13 @@ pub struct DimensionTool { snap: crate::guides::DrawSnap, /// Where the next Linear pick lands, as last worked out for the pointer (for the overlays). snapped: Option<(Point, Option)>, + /// Whether the press under way began on an anchor a Linear click picks. + press_on_anchor: bool, } +/// How near an anchor (screen pixels) a pick snaps to it. +const ANCHOR_REACH: f64 = 8.0; + /// `at` as a Shift click picks it: the direction from `last` snapped to 45° steps (from the /// constrain angle), the distance kept. fn constrained(cx: &ToolContext, last: Point, at: Point) -> Point { @@ -119,10 +124,45 @@ fn anchor_near(cx: &ToolContext, edge: &SegmentRef, p: Point) -> Option<(usize, [edge.segment, next] .into_iter() .filter_map(|i| Some((i, sp.anchors.get(i)?.p))) - .filter(|(_, a)| a.distance(p) <= cx.tol(8.0)) + .filter(|(_, a)| a.distance(p) <= cx.tol(ANCHOR_REACH)) .min_by(|(_, a), (_, b)| a.distance(p).total_cmp(&b.distance(p))) } +/// The anchor nearest `p` within reach, on any editable path (the topmost on a tie), as a link to +/// its path. Bounded work, and dimension artwork is skipped, as in [`pick`]. +fn anchor_under(cx: &ToolContext, p: Point) -> Option<(Point, PointRef)> { + type Best = Option<(f64, Point, PointRef)>; + fn visit(n: &Node, p: Point, reach: f64, budget: &mut usize, best: &mut Best) { + if *budget == 0 || !n.visible || n.locked || n.extras().dimension.is_some() { + return; + } + if let Some(path) = n.path_data() { + for (subpath, sp) in path.subpaths.iter().enumerate() { + for (anchor, a) in sp.anchors.iter().enumerate() { + if *budget == 0 { + return; + } + *budget -= 1; + let d = a.p.distance(p); + if d <= reach && best.as_ref().is_none_or(|(nearest, ..)| d < *nearest) { + *best = Some((d, a.p, PointRef { node: n.id, subpath, anchor })); + } + } + } + } + if let Some(ch) = n.children() { + for c in ch.iter().rev() { + visit(c, p, reach, budget, best); + } + } + } + let (reach, mut budget, mut best) = (cx.tol(ANCHOR_REACH), 20_000usize, None); + for n in cx.doc.layers.iter().rev() { + visit(n, p, reach, &mut budget, &mut best); + } + best.map(|(_, at, r)| (at, r)) +} + /// The point of `edge` closest to `p`. fn nearest_on(cx: &ToolContext, edge: &SegmentRef, p: Point) -> Option { use vectorcraft_geom::kurbo::ParamCurveNearest; @@ -138,25 +178,22 @@ fn nearest_on(cx: &ToolContext, edge: &SegmentRef, p: Point) -> Option { } impl DimensionTool { - /// Where a Linear pick at `p` lands: on an anchor of the line under the pointer, within reach - /// (kept as a link to its path); else where Smart Guides put it (another object's anchor or - /// centre, in line with one, or for the second point on a construction guide through the - /// first), its guides showing; else on the closest point of that line; else `p` itself. + /// Where a Linear pick at `p` lands: on the nearest anchor of any path, within reach (kept as + /// a link to its path); else where Smart Guides put it (another object's anchor or centre, in + /// line with one, or for the second point on a construction guide through the first), its + /// guides showing; else on the closest point of the line under the pointer; else `p` itself. fn snap_linear(&mut self, cx: &ToolContext, p: Point) -> (Point, Option) { let leave = self.points.last().map(|(first, _)| crate::guides::Leave::segment(cx, *first, false)); let guided = self.snap.hover(cx, p, &[], leave.as_ref()); - let edge = pick(cx, p); - if let Some(edge) = &edge - && let Some((anchor, point)) = anchor_near(cx, edge, p) - { + if let Some((point, reference)) = anchor_under(cx, p) { self.snap.clear(); - return (point, Some(PointRef { node: edge.node, subpath: edge.subpath, anchor })); + return (point, Some(reference)); } if guided.distance(p) > 1e-9 { return (guided, None); } // Not on an anchor or a guide: snap to the closest point of the line (#2432). - (edge.and_then(|e| nearest_on(cx, &e, p)).unwrap_or(p), None) + (pick(cx, p).and_then(|e| nearest_on(cx, &e, p)).unwrap_or(p), None) } fn target(&self, cx: &ToolContext, p: Point) -> Option { let edge = pick(cx, p)?; @@ -243,6 +280,7 @@ impl DimensionTool { fn reset(&mut self) { self.pending = None; self.press = None; + self.press_on_anchor = false; self.points.clear(); self.lines.clear(); self.dragging = false; @@ -355,6 +393,10 @@ impl Tool for DimensionTool { self.press = Some((ev.pos, None)); return self.preview(cx, ev.pos); } + // A Linear press on an anchor picks the anchor unless it drags past the anchor's + // reach: moving a few pixels before the release does not drag out the dimension of + // a segment under the pointer. + self.press_on_anchor = self.kind == Kind::Linear && anchor_under(cx, ev.pos).is_some(); self.press = Some((ev.pos, self.target(cx, ev.pos))); vec![] } @@ -364,7 +406,7 @@ impl Tool for DimensionTool { } if self.pending.is_none() && let Some((start, Some(target))) = self.press.clone() - && start.distance(ev.pos) > cx.tol(3.0) + && start.distance(ev.pos) > cx.tol(if self.press_on_anchor { ANCHOR_REACH } else { 3.0 }) && self.points.is_empty() && self.lines.is_empty() { @@ -543,6 +585,76 @@ mod tests { assert!(matches!(placed.last(), Some(Action::Commit)), "{placed:?}"); } + /// A Linear press on an anchor picks that anchor even when the pointer moves a few pixels + /// before the release: it does not drag out the dimension of a segment that ends there. Both + /// picks keep their links to the path, so the dimension measures between the two anchors. + #[test] + fn a_press_on_an_anchor_picks_it_when_the_pointer_moves() { + let (d, id) = doc_with_rect(); + let (s, p) = (Selection::default(), paint()); + let c = cx(&d, &s, &p); + let ev = |kind, x: f64, y: f64| PointerEvent::new(kind, x, y); + let mut t = DimensionTool::default(); + for ((x, y), (dx, dy)) in [((100.0, 100.0), (3.5, 1.0)), ((200.0, 200.0), (-4.0, -2.0))] { + assert!(t.pointer(&c, &ev(PointerKind::Down, x, y)).is_empty()); + assert!(t.pointer(&c, &ev(PointerKind::Drag, x + dx, y + dy)).is_empty(), "no segment dimension is dragged out"); + assert!(t.pointer(&c, &ev(PointerKind::Up, x + dx, y + dy)).is_empty(), "nothing is committed"); + } + let d = t.pending.as_ref().expect("both anchors were picked"); + assert_eq!((d.a, d.b), (Point::new(100.0, 100.0), Point::new(200.0, 200.0))); + let anchor = |anchor| Some(PointRef { node: id, subpath: 0, anchor }); + assert_eq!(d.source, Some(DimensionSource::Points { a: anchor(0), b: anchor(2), vertex: None })); + // Dragged past the anchor's reach, the press drags out the dimension of a segment there. + let mut t = DimensionTool::default(); + t.pointer(&c, &ev(PointerKind::Down, 100.0, 100.0)); + assert!(t.pointer(&c, &ev(PointerKind::Drag, 103.0, 106.0)).is_empty()); + let acts = t.pointer(&c, &ev(PointerKind::Drag, 100.0, 60.0)); + assert!(matches!(acts.first(), Some(Action::Begin(_))), "{acts:?}"); + assert!(matches!(t.pointer(&c, &ev(PointerKind::Up, 100.0, 60.0)).last(), Some(Action::Commit))); + } + + /// The anchors of a live rectangle are picked the same way. + #[test] + fn a_press_on_a_live_shapes_anchor_picks_it() { + let (d, id) = doc_with_live_rect(); + let (s, p) = (Selection::default(), paint()); + let c = cx(&d, &s, &p); + let mut t = DimensionTool::default(); + t.pointer(&c, &PointerEvent::new(PointerKind::Down, 200.0, 100.0)); + t.pointer(&c, &PointerEvent::new(PointerKind::Drag, 197.0, 102.0)); + t.pointer(&c, &PointerEvent::new(PointerKind::Up, 197.0, 102.0)); + let [(at, Some(r))] = t.points.as_slice() else { panic!("{:?}", t.points) }; + assert_eq!((*at, r.node), (Point::new(200.0, 100.0), id)); + } + + /// An anchor of a compound path inside nested groups, lying just inside another object's + /// edge, is picked and linked, though that edge is nearer the pointer than any of the + /// compound path's own segments. A press there that moves a few pixels picks it too. + #[test] + fn an_anchor_under_another_objects_edge_is_picked() { + use std::sync::Arc; + use vectorcraft_doc::{Appearance, NodeKind}; + use vectorcraft_geom::Rect; + let (mut d, _) = doc_with_rect(); + let l = d.layers[0].id; + let (outer, inner, compound) = (d.alloc_id(), d.alloc_id(), d.alloc_id()); + let mut path = vectorcraft_geom::shapes::rectangle(Rect::new(20.0, 20.0, 40.0, 40.0)); + path.subpaths.extend(vectorcraft_geom::shapes::rectangle(Rect::new(150.0, 103.0, 180.0, 130.0)).subpaths); + let art = Node::path(compound, path, Appearance::default_art()); + let inner_group = Node::new(inner, NodeKind::Group { children: vec![Arc::new(art)], clip: false }); + let group = Node::new(outer, NodeKind::Group { children: vec![Arc::new(inner_group)], clip: false }); + d.insert(Some(l), 0, group).unwrap(); + let (s, p) = (Selection::default(), paint()); + let c = cx(&d, &s, &p); + let corner = (Point::new(150.0, 103.0), Some(PointRef { node: compound, subpath: 1, anchor: 0 })); + let mut t = DimensionTool::default(); + assert_eq!(t.snap_linear(&c, Point::new(151.0, 101.0)), corner); + t.pointer(&c, &PointerEvent::new(PointerKind::Down, 151.0, 101.0)); + assert!(t.pointer(&c, &PointerEvent::new(PointerKind::Drag, 155.0, 100.0)).is_empty(), "no segment dimension is dragged out"); + t.pointer(&c, &PointerEvent::new(PointerKind::Up, 155.0, 100.0)); + assert_eq!(t.points, vec![corner]); + } + #[test] fn placement_press_previews_without_a_prior_move() { let (d, _) = doc_with_rect(); diff --git a/crates/tools/src/direct.rs b/crates/tools/src/direct.rs index 833f482255..1477cd5bba 100644 --- a/crates/tools/src/direct.rs +++ b/crates/tools/src/direct.rs @@ -557,7 +557,7 @@ fn hit_frame_edge(cx: &ToolContext, p: Point, tol: f64) -> Option<(NodeId, Vec Vec<(NodeId, usize, usize, Anchor)> { let mut v = vec![]; for &id in &cx.selection.objects { - let Some(pd) = cx.doc.node(id).and_then(|n| n.path_data()) else { continue }; + let Some(pd) = cx.doc.node(id).and_then(handle_path) else { continue }; let shown = cx.selection.partial(id); v.extend(pd.anchors().filter(|(si, ai, _)| shown.is_none_or(|set| set.contains(&(*si, *ai)))).map(|(si, ai, a)| { let mut a = *a; @@ -579,6 +579,33 @@ fn handle_anchors(cx: &ToolContext) -> Vec<(NodeId, usize, usize, Anchor)> { v } +/// The path whose direction handles Direct Selection shows and drags on `n` once it is selected: +/// a path's, or type on a path's path (#3565), in document space. +fn handle_path(n: &Node) -> Option> { + match &n.kind { + NodeKind::Path { path, .. } => Some(Cow::Borrowed(path)), + NodeKind::Text(t) if is_path_type(n) => t.type_path().map(Cow::Owned), + _ => None, + } +} + +/// The direction handles of selected type on a path ([`handle_anchors`]), drawn by the tool: +/// the canvas draws only a path's own (#3565). +fn type_path_handles(cx: &ToolContext) -> Vec { + let mut out = vec![]; + for (id, _, _, a) in handle_anchors(cx) { + if !cx.doc.node(id).is_some_and(is_path_type) { + continue; + } + let color = cx.doc.layer_color(id); + for h in [a.h_in, a.h_out].into_iter().filter(|h| h.distance(a.p) > 1e-6) { + out.push(Overlay::Line { a: a.p, b: h, color, dashed: false }); + out.push(Overlay::Handle { p: h, color }); + } + } + out +} + /// The end of a shown direction handle ([`handle_anchors`]) nearest to `p` within `tol`, and /// nearer to it than the handle's anchor (a short handle leaves its anchor to be picked): (path, /// subpath, anchor, is_out). @@ -897,8 +924,9 @@ impl Tool for DirectSelectionTool { let (q, guides) = self.handle_snap.snap(cx, (id, si, ai), p, ev.mods.shift); self.snapped = snapped(q.to_vec2(), p.to_vec2(), ev.mods.shift, &guides); self.guides = guides; + let cmd = if cx.doc.node(id).is_some_and(is_path_type) { "text.setPathHandle" } else { "path.setHandle" }; vec![Action::Preview( - "path.setHandle".into(), + cmd.into(), json!({"id": id.0, "subpath": si, "anchor": ai, "which": if out {"out"} else {"in"}, "x": q.x, "y": q.y, "independent": ev.mods.alt}), )] } @@ -1001,6 +1029,7 @@ impl Tool for DirectSelectionTool { out.push(Overlay::Path { path, color: cx.doc.layer_color(sp.instance), width: 1.0, dashed: false }); } out.extend(frame_overlays(cx, &self.frame_anchors(cx))); + out.extend(type_path_handles(cx)); let drag = if let State::Bracket(b) = &self.state { Some(b) } else { None }; out.extend(pathtype::overlays(cx, self.bracket_hover, drag)); } diff --git a/crates/tools/src/direct/tests.rs b/crates/tools/src/direct/tests.rs index 7948b47072..d7d4bb85b4 100644 --- a/crates/tools/src/direct/tests.rs +++ b/crates/tools/src/direct/tests.rs @@ -2334,3 +2334,38 @@ fn a_press_on_a_clipping_path_in_a_dynamic_instance_picks_it() { outline.iter().find_map(|o| if let Overlay::Path { path, .. } = o { Some(vectorcraft_geom::kurbo::Shape::bounding_box(path)) } else { None }); assert_eq!(drawn, Some(Rect::new(310.0, 310.0, 320.0, 320.0))); } + +/// #3565: selected type on a path shows its path's direction handles, as a path selected whole +/// shows its own, and a press on one drags it with `text.setPathHandle` (Shift: 45° steps round +/// its anchor; Alt: that side only); none with Show handles when multiple anchors are selected off. +#[test] +fn type_on_a_path_shows_and_drags_its_paths_handles() { + let (mut d, text) = doc_with_path_type(); + let Some(vectorcraft_doc::NodeKind::Text(t)) = d.node_mut(text).map(|n| &mut n.kind) else { panic!("type") }; + let vectorcraft_doc::TextKind::OnPath { path, .. } = &mut t.kind else { panic!("on a path") }; + path.subpaths[0].anchors[0].h_out = Point::new(100.0, 200.0); + path.subpaths[0].anchors[1].h_in = Point::new(400.0, 200.0); + let p = paint(); + let mut s = Selection::default(); + s.add(text); + let c = cx(&d, &s, &p); + let handles = |c: &ToolContext| -> Vec { + DirectSelectionTool::new(false).overlays(c).iter().filter_map(|o| if let Overlay::Handle { p, .. } = o { Some(*p) } else { None }).collect() + }; + assert_eq!(handles(&c), vec![Point::new(100.0, 200.0), Point::new(400.0, 200.0)]); + let mut t = DirectSelectionTool::new(false); + assert_eq!(t.pointer(&c, &PointerEvent::new(PointerKind::Down, 101.0, 201.0)), vec![Action::Begin("Reshape".into())]); + let a = t.pointer(&c, &PointerEvent::new(PointerKind::Drag, 130.0, 210.0).with_mods(Mods { alt: true, ..Mods::default() })); + assert!( + matches!(&a[..], [Action::Preview(n, v)] if n == "text.setPathHandle" && v["id"] == text.0 && v["subpath"] == 0 && v["anchor"] == 0 && v["which"] == "out" && v["independent"] == true), + "{a:?}" + ); + assert_eq!(t.pointer(&c, &PointerEvent::new(PointerKind::Up, 130.0, 210.0)), vec![Action::Commit]); + let mut t = DirectSelectionTool::new(false); + t.pointer(&c, &PointerEvent::new(PointerKind::Down, 399.0, 201.0)); + let a = t.pointer(&c, &PointerEvent::new(PointerKind::Drag, 390.0, 120.0).with_mods(Mods { shift: true, ..Mods::default() })); + let Some(Action::Preview(n, v)) = a.first() else { panic!("{a:?}") }; + assert_eq!((n.as_str(), &v["anchor"], &v["which"]), ("text.setPathHandle", &json!(1), &json!("in"))); + assert!((v["x"].as_f64().unwrap() - 400.0).abs() < 1e-9, "Shift keeps it straight above its anchor: {v}"); + assert!(handles(&ToolContext { handles_multiple: false, ..cx(&d, &s, &p) }).is_empty()); +} diff --git a/crates/tools/src/draw2/curvature.rs b/crates/tools/src/draw2/curvature.rs index 70ad9a7e4a..b92f8adfba 100644 --- a/crates/tools/src/draw2/curvature.rs +++ b/crates/tools/src/draw2/curvature.rs @@ -649,6 +649,10 @@ impl Tool for CurvatureTool { self.id = Some(cx.selection.objects[0]); } } + /// A path being drawn: Escape ends it. + fn ends_on_escape(&self, cx: &ToolContext) -> bool { + self.active(cx).is_some() + } fn claims_key(&self, cx: &ToolContext, key: ToolKey) -> bool { matches!(key, ToolKey::Backspace | ToolKey::Delete) && self.drag.is_none() diff --git a/crates/tools/src/guides/snap.rs b/crates/tools/src/guides/snap.rs index 9d530f4db5..32941c5f71 100644 --- a/crates/tools/src/guides/snap.rs +++ b/crates/tools/src/guides/snap.rs @@ -428,8 +428,12 @@ impl HandleSnap { /// Where the handle of anchor `ai` of subpath `si` of path `id` goes with the pointer at `p`, /// and the guides showing why. pub fn snap(&mut self, cx: &ToolContext, (id, si, ai): (NodeId, usize, usize), p: Point, shift: bool) -> (Point, Vec) { - let path = cx.doc.node(id).and_then(|n| n.path_data()); - if shift && let Some(a) = path.and_then(|pd| pd.subpaths.get(si)?.anchors.get(ai)) { + // A path's anchor, or one of type on a path's path (#3565), in document space. + let anchor = cx.doc.node(id).and_then(|n| match &n.kind { + vectorcraft_doc::NodeKind::Text(t) => t.type_path()?.subpaths.get(si)?.anchors.get(ai).copied(), + _ => n.path_data()?.subpaths.get(si)?.anchors.get(ai).copied(), + }); + if shift && let Some(a) = anchor { return (a.p + constrain_angle_from(p - a.p, 45.0, cx.constrain_angle), vec![]); } if self.0.targets.is_none() { diff --git a/crates/tools/src/lib.rs b/crates/tools/src/lib.rs index b4a7d69971..c397231495 100644 --- a/crates/tools/src/lib.rs +++ b/crates/tools/src/lib.rs @@ -162,6 +162,12 @@ pub trait Tool: Send { fn claims_key(&self, _cx: &ToolContext, _key: ToolKey) -> bool { false } + /// Has the tool started something that Escape ends while no button is pressed (a path being + /// drawn, the Blend tool's first pick)? That Escape ends nothing else, such as isolation mode or + /// a rotated view. + fn ends_on_escape(&self, _cx: &ToolContext) -> bool { + false + } /// Does the tool want typed text (Type tool editing)? Single-key shortcuts are suppressed. fn wants_text(&self) -> bool { false diff --git a/crates/tools/src/meshblend.rs b/crates/tools/src/meshblend.rs index 5edc14ad42..d64b4b162b 100644 --- a/crates/tools/src/meshblend.rs +++ b/crates/tools/src/meshblend.rs @@ -153,6 +153,10 @@ impl Tool for BlendTool { fn busy(&self) -> bool { self.first.is_some() } + /// A first pick, or adding to the blend just made: Escape ends either. + fn ends_on_escape(&self, cx: &ToolContext) -> bool { + self.first(cx).is_some() + } /// Escape drops the object picked first and stops adding to the blend just made, so the next /// click picks a new first object. The document and the selection stay as they are. fn key(&mut self, _cx: &ToolContext, key: crate::ToolKey, _mods: Mods) -> Vec { @@ -525,8 +529,10 @@ mod tests { let c = cx(&d, &s, &p); let mut t = BlendTool { first: None, chained: true, ..Default::default() }; assert!(t.first(&c).is_some()); + assert!(!t.busy() && t.ends_on_escape(&c), "Escape has adding to the blend to end"); assert!(t.key(&c, crate::ToolKey::Escape, Mods::default()).is_empty()); assert!(t.first(&c).is_none(), "Escape ends adding to the blend just made"); + assert!(!t.ends_on_escape(&c), "and then has nothing to end"); assert_eq!(t.pointer(&c, &down(150.0, 150.0)), picks(a)); assert!(esc(&mut BlendTool::default()).is_empty(), "nothing to drop"); } diff --git a/crates/tools/src/pen.rs b/crates/tools/src/pen.rs index e5906db59f..bc564fced3 100644 --- a/crates/tools/src/pen.rs +++ b/crates/tools/src/pen.rs @@ -242,6 +242,10 @@ impl Tool for PenTool { fn busy(&self) -> bool { self.drag.is_some() || self.handle.is_some() || self.convert.is_some() } + /// A path being drawn: Escape ends it. + fn ends_on_escape(&self, _cx: &ToolContext) -> bool { + self.path.is_some() + } fn pointer(&mut self, cx: &ToolContext, ev: &PointerEvent) -> Vec { let tol = cx.tol(5.0).max(cx.point_tol()); // The path a press began is the selected one by the next event. diff --git a/crates/ui-egui/src/app.rs b/crates/ui-egui/src/app.rs index 49775e2419..0f5152d2bb 100644 --- a/crates/ui-egui/src/app.rs +++ b/crates/ui-egui/src/app.rs @@ -53,6 +53,8 @@ impl VectorcraftApp { // The place cursor's clicks and drags place their files through the app // ([`place::place_from_cursor`]). session.place_cursor_requests = true; + // A script runs a slice per frame, so the window keeps drawing and Stop can be pressed. + session.script_frames = true; let views = session.documents().iter().map(View::of).collect(); let view_uids = session.documents().iter().map(|d| d.uid).collect(); let known = session.documents().iter().map(|d| d.uid).collect(); @@ -124,6 +126,7 @@ impl VectorcraftApp { updates_rt: Default::default(), frame_rate: Default::default(), canvas_rect: None, + control_rotate_press: None, hover_doc: None, titlebar_from_env: false, custom_titlebar: false, @@ -232,6 +235,19 @@ impl VectorcraftApp { /// eframe isn't a dependency of this crate (the host owns the event loop); these entry points are /// called from the host's `eframe::App` impl. impl VectorcraftApp { + /// Applies the work that finished off the UI thread. It stays pending while a script runs, since + /// every change to the documents ends in a busy error until the script ends. + pub(crate) fn poll_finished_work(&mut self) { + if self.session.script_running() { + return; + } + background::poll(self); + opening::poll(self); + plugin_runs::poll(self); + trace_runs::poll(self); + placing::poll(self); + } + /// The language the UI is drawn in: the Preferences dialog's choice while it is open (so a /// change shows before OK), else the `interfaceLanguage` preference (`auto` = the system's). pub fn ui_language(&self) -> i18n::Lang { @@ -321,12 +337,12 @@ impl VectorcraftApp { // A Paste the host read before this iteration's formats were written must still wait for // them, even if the worker below finishes them during this same tick. ctx.data_mut(|d| d.insert_temp(egui::Id::unique("clipboard.pending-at-tick"), self.clipboard_publishing.is_pending())); - background::poll(self); screen_color::poll(self, ctx); - opening::poll(self); - plugin_runs::poll(self); - trace_runs::poll(self); - placing::poll(self); + self.poll_finished_work(); + crate::script_runs::poll(self); + if self.session.script_running() && !self.session.script_waiting() { + ctx.request_repaint(); + } #[cfg(not(target_arch = "wasm32"))] self.tick_link_updates(ctx, now); crate::addons::select::link_status::refresh(self, now); @@ -351,7 +367,12 @@ impl VectorcraftApp { crate::ime::close_viewport(self, ctx); self.ime_context.end_viewport(ctx.viewport_id()); unsaved::finish_pending(self); - if self.file_sheet_open() { + if self.session.script_running() { + ctx.send_viewport_cmd(egui::ViewportCommand::CancelClose); + if self.ui.dialog.is_none() { + self.ui.dialog = Some(crate::state::Dialog::new(dialogs::script_run::CLOSE_KIND, serde_json::json!({}))); + } + } else if self.file_sheet_open() { ctx.send_viewport_cmd(egui::ViewportCommand::CancelClose); self.status(picks::busy()); } else if unsaved::any_dirty(self) { diff --git a/crates/ui-egui/src/app/commands.rs b/crates/ui-egui/src/app/commands.rs index d5ca8a1968..9e698b1bff 100644 --- a/crates/ui-egui/src/app/commands.rs +++ b/crates/ui-egui/src/app/commands.rs @@ -404,6 +404,10 @@ impl VectorcraftApp { if let Err(e) = switched { self.ui.status = e.to_string(); } + if before != self.session.tool_id() { + // A control gesture cannot resume after another tool has owned the pointer. + self.control_rotate_press = None; + } // A newly chosen Artboard tool starts on the active artboard (the view's). if before != "artboard" && self.session.tool_id() == "artboard" diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs index ed9c62d0b7..6fc9baab5c 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -77,6 +77,7 @@ use tool_overlays::{ print_tiling_overlay, rotate_view_dial, shaper_widget_overlay, slice_overlay, spelling_overlay, thread_overlays, }; pub(crate) use view::animated_zoom; +pub(crate) use view::drag_rotation; pub use view::fit; use view::scroll_bars; #[cfg(test)] @@ -543,8 +544,9 @@ fn ruler_bands(app: &VectorcraftApp, ui: &Ui, xf: &Xf, (full, rect): (egui::Rect let painter = ui.painter_at(rect); if let Some(origin) = origin_preview { let at = xf.to_screen(origin); - painter.line_segment([pos2(at.x, rect.top()), pos2(at.x, rect.bottom())], Stroke::new(1.0, t.text_dim)); - painter.line_segment([pos2(rect.left(), at.y), pos2(rect.right(), at.y)], Stroke::new(1.0, t.text_dim)); + let color = dim_on_canvas(t, app.outline_view()); + painter.line_segment([pos2(at.x, rect.top()), pos2(at.x, rect.bottom())], Stroke::new(1.0, color)); + painter.line_segment([pos2(rect.left(), at.y), pos2(rect.right(), at.y)], Stroke::new(1.0, color)); } // View › Rulers › Show Video Rulers counts the active artboard in video pixels. let video = app.ui.view.video_rulers.then(|| crate::dialogs::artboard_options::active_index(app)); @@ -793,8 +795,17 @@ fn draw_frame(app: &mut VectorcraftApp, ui: &Ui, frame: Frame) { } } -/// The pasteboard, the artboards' shadows and paper, and the outline mode's white artboards, of -/// document `st`, in Outline when `outline`. +/// The canvas color in Outline, whatever the interface brightness and Canvas Color: the paths draw +/// as black hairlines, and the artboards as their edges only. +const OUTLINE_CANVAS: Color32 = Color32::WHITE; + +/// The color of the artboards' names and the ruler origin's crosshair in Outline, on +/// [`OUTLINE_CANVAS`]. +const OUTLINE_DIM: Color32 = Color32::from_gray(0x4b); + +/// The pasteboard and the artboards' shadows and paper of document `st`, or in Outline (`outline`) +/// the whole canvas in [`OUTLINE_CANVAS`], with no paper drawn for the artboards: no Simulate +/// Colored Paper color, no artboard background color, and no paper with View › Hide Artboards. fn paint_paper( app: &VectorcraftApp, st: &vectorcraft_engine::DocState, @@ -805,6 +816,12 @@ fn paint_paper( (t, outline): (&Tokens, bool), ) { let doc = &st.doc; + if outline { + // The art draws in black on white over the pasteboard and the artboards alike, and the + // artboards show as their edges (`artboard_outlines`). + painter.rect_filled(rect, 0.0, OUTLINE_CANVAS); + return; + } // Pasteboard, artboard shadows and paper (Document Setup: the transparency grid's look, the // simulated paper colour; a white Background Contents hides the grid). // An artboard with a background color draws its paper in that color. With Simulate Colored Paper @@ -815,7 +832,7 @@ fn paint_paper( // View › Hide Artboards: no edges and no pasteboard, the whole canvas paper (#4038). let setup = &doc.setup; painter.rect_filled(rect, 0.0, if setup.simulate_paper { crate::panels::c32(&setup.paper()) } else { Color32::WHITE }); - } else if !outline { + } else { let setup = &doc.setup; let grid = (st.transparency_grid && setup.background == vectorcraft_doc::Background::Transparent).then(|| checker_texture(ui.ctx(), setup)); let paper = if setup.simulate_paper { crate::panels::c32(&setup.paper()) } else { Color32::WHITE }; @@ -833,10 +850,6 @@ fn paint_paper( } } } - } else { - for ab in &doc.artboards { - painter.add(Shape::convex_polygon(xf.quad(ab.rect), Color32::WHITE, Stroke::NONE)); - } } } @@ -1007,16 +1020,22 @@ fn artboard_outlines(app: &VectorcraftApp, ui: &Ui, painter: &egui::Painter, xf: let tool_selected = artboards::tool_labelled(app); let editing_name = ui.data(|d| d.get_temp::(name_edit_id()).map(|e| e.index)); let unlabelled = |i: usize| editing_name == Some(i) || u64::try_from(i).ok().is_some_and(|idx| tool_selected.contains(&idx)); - artboard_edges(app, doc, (painter, xf, t), active_ab, unlabelled); + artboard_edges(app, doc, (painter, xf, t), (active_ab, dim_on_canvas(t, app.outline_view())), unlabelled); } -/// The edges, bleeds, marks and names of `doc`'s artboards, `active_ab` the active one; the -/// artboards `unlabelled` gives are not named. +/// The color of the artboards' names and the ruler origin's crosshair over the pasteboard, or over +/// [`OUTLINE_CANVAS`] in Outline (`outline`). +fn dim_on_canvas(t: &Tokens, outline: bool) -> Color32 { + if outline { OUTLINE_DIM } else { t.text_dim } +} + +/// The edges, bleeds, marks and names of `doc`'s artboards, `active_ab` the active one, the names +/// in `label`; the artboards `unlabelled` gives are not named. fn artboard_edges( app: &VectorcraftApp, doc: &vectorcraft_doc::Document, (painter, xf, t): (&egui::Painter, &Xf, &Tokens), - active_ab: usize, + (active_ab, label): (usize, Color32), unlabelled: impl Fn(usize) -> bool, ) { let artboard_tool = app.session.tool_id() == "artboard"; @@ -1034,7 +1053,7 @@ fn artboard_edges( // At the artboard's own top-left corner, which a rotated view turns away from its // bounding box's (#1095). let corner = xf.to_screen(Point::new(ab.rect.x0, ab.rect.y0)); - artboard_label(painter, corner, (ab.rect.width() * xf.zoom) as f32, &format!("{:02} - {}", i + 1, ab.name), t.text_dim); + artboard_label(painter, corner, (ab.rect.width() * xf.zoom) as f32, &format!("{:02} - {}", i + 1, ab.name), label); } } } diff --git a/crates/ui-egui/src/canvas/input.rs b/crates/ui-egui/src/canvas/input.rs index 5fbc2b9038..43e5df0bcd 100644 --- a/crates/ui-egui/src/canvas/input.rs +++ b/crates/ui-egui/src/canvas/input.rs @@ -337,14 +337,8 @@ fn drag_held(app: &mut VectorcraftApp, ui: &Ui, f: &Pointing, d: Drag, p: Pos2) } } Drag::RotateView { start_angle, start_rot, snaps } => { - let c = rect.center(); - let a = (p.y - c.y).atan2(p.x - c.x) as f64; - let mut deg = start_rot + (a - start_angle).to_degrees(); - if snaps && m.shift { - deg = (deg / 15.0).round() * 15.0; - } if let Some(vm) = app.view_mut() { - vm.rotation = vectorcraft_geom::normalize_deg(deg); + vm.rotation = super::view::drag_rotation(rect.center(), p, start_angle, start_rot, snaps && m.shift); } } Drag::ZoomBox { start } => { diff --git a/crates/ui-egui/src/canvas/panes.rs b/crates/ui-egui/src/canvas/panes.rs index 5bd974bf92..13b56e6f1e 100644 --- a/crates/ui-egui/src/canvas/panes.rs +++ b/crates/ui-egui/src/canvas/panes.rs @@ -12,7 +12,8 @@ use super::outline::{c32, node_outline, stroke_path, too_many_anchors}; use super::view::fit_zoom; use super::{ Affine, CacheKey, Point, Rect, RulerScale, Sense, Stroke, StrokeKind, Tokens, Ui, VectorcraftApp, View, Xf, artboard_edges, cache_key, - frame_options, frame_view, grid, guides_of, json, paint_paper, pixel_region, pos2, rulers, shows_artboards, textured_quad, vec2, view_rects, + dim_on_canvas, frame_options, frame_view, grid, guides_of, json, paint_paper, pixel_region, pos2, rulers, shows_artboards, textured_quad, vec2, + view_rects, }; use crate::doc_windows::Win; use crate::thumb_worker::ThumbWorker; @@ -315,7 +316,7 @@ pub(crate) fn pane(app: &mut VectorcraftApp, ui: &Ui, w: Win, cell: egui::Rect) grid(&painter, &xf, st.doc.grid.spacing, st.doc.grid.subdivisions, look); } if shows_artboards(app) { - artboard_edges(app, &st.doc, (&painter, &xf, &t), v.artboard, |_| false); + artboard_edges(app, &st.doc, (&painter, &xf, &t), (v.artboard, dim_on_canvas(&t, v.outline)), |_| false); } if app.ui.view.guides { guides_of(app, st, (&painter, &xf, &t), rect); diff --git a/crates/ui-egui/src/canvas/tests.rs b/crates/ui-egui/src/canvas/tests.rs index 42778c729f..047ee9fa7b 100644 --- a/crates/ui-egui/src/canvas/tests.rs +++ b/crates/ui-egui/src/canvas/tests.rs @@ -210,6 +210,27 @@ fn command_cursor_settings_refresh_hover_cursor_while_view_moves() { assert_eq!(hover_cursor(&mut app, mods, view, false), Some(Cursor::Crosshair)); } +/// A script that changes Caps Lock refreshes the pointer when its run ends. +#[test] +fn a_script_run_refreshes_hover_cursor_while_view_moves() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); + app.session.select_tool("pen", vectorcraft_engine::ViewInfo::default()).unwrap(); + app.hover_doc = Some(Point::new(200.0, 150.0)); + let mods = Mods::default(); + let view = vectorcraft_engine::ViewInfo::default(); + assert_eq!(hover_cursor(&mut app, mods, view, false), Some(Cursor::Pen)); + app.run("script.run", json!({"source": "vc.run('view.capsLock', {on: true});"})).unwrap(); + for _ in 0..1_000 { + if !app.session.script_running() { + break; + } + crate::script_runs::poll(&mut app); + } + assert!(app.session.caps_lock); + assert_eq!(hover_cursor(&mut app, mods, view, false), Some(Cursor::Crosshair)); +} + /// #826: in a turned view each ruler still has ticks along its whole length; at 0° the top one /// reads x where the canvas has it. #[test] @@ -4189,6 +4210,203 @@ fn outline_is_per_document_and_new_documents_start_in_preview() { assert!(app.run("view.outline", json!({})).is_err()); } +/// One headless canvas frame → (the colors of the filled rectangles that cover the canvas, the +/// fills of the shapes laid over an artboard, the artboards' edges drawn, the colors of the +/// artboards' names). +fn canvas_look(app: &mut VectorcraftApp, ctx: &egui::Context) -> (Vec, Vec, usize, Vec) { + let s = shapes(app, ctx); + let canvas = app.canvas_rect.unwrap(); + let xf = Xf::new(canvas, app.view().unwrap()); + let quads: Vec> = app.session.active().unwrap().doc.artboards.iter().map(|a| xf.quad(a.rect).to_vec()).collect(); + let on = |p: &[Pos2]| quads.iter().any(|q| q.len() == p.len() && q.iter().zip(p).all(|(a, b)| (*a - *b).length() < 0.01)); + let covers: Vec = s + .iter() + .filter_map(|s| match s { + Shape::Rect(r) if r.rect.contains_rect(canvas) => Some(r.fill), + _ => None, + }) + .collect(); + let papers: Vec = s + .iter() + .filter_map(|s| match s { + Shape::Path(p) if p.fill != Color32::TRANSPARENT && on(&p.points) => Some(p.fill), + _ => None, + }) + .collect(); + let edges = s.iter().filter(|s| matches!(s, Shape::Path(p) if p.closed && p.fill == Color32::TRANSPARENT && on(&p.points))).count(); + let names: Vec = s + .iter() + .filter_map(|s| match s { + Shape::Text(t) if names_an_artboard(t.galley.text()) => Some(t.fallback_color), + _ => None, + }) + .collect(); + (covers, papers, edges, names) +} + +/// In Outline, in every interface brightness, color scheme and User Interface › Canvas Color, the +/// whole canvas is white, pasteboard included, so the black outlines of art on the pasteboard show. +/// The artboards draw no paper there, only their edges, and their names draw in a dark gray. In +/// Preview the pasteboard keeps its color and the artboards their white paper. +#[test] +fn outline_draws_on_a_white_canvas_with_artboards_as_edges() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.session.execute("file.new", &json!({"width": 200, "height": 100, "artboards": 2})).unwrap(); + for brightness in crate::theme::Brightness::ALL { + for scheme in crate::theme::Scheme::ALL { + // Canvas Color: matching the brightness, Dark Gray and Medium Gray, as `prefs_dialog` sets it. + for canvas_color in [None, Some(Color32::from_gray(0x5a)), Some(Color32::from_gray(0x96))] { + let ctx = egui::Context::default(); + crate::theme::apply_with(&ctx, brightness, Default::default(), scheme); + if let Some(c) = canvas_color { + let mut t = Tokens::get(&ctx); + t.pasteboard = c; + ctx.data_mut(|d| d.insert_temp(egui::Id::NULL, t)); + } + let case = format!("{brightness:?} {scheme:?} {canvas_color:?}"); + let pasteboard = Tokens::get(&ctx).pasteboard; + assert_ne!(pasteboard, Color32::WHITE, "{case}"); + app.view_mut().unwrap().outline = false; + let (covers, papers, edges, names) = canvas_look(&mut app, &ctx); + assert_eq!(covers.last(), Some(&pasteboard), "{case}: Preview keeps the pasteboard"); + assert_eq!(papers, [Color32::WHITE; 2], "{case}: and the artboards' paper"); + assert_eq!(edges, 2, "{case}"); + assert_eq!(names, [Tokens::get(&ctx).text_dim; 2], "{case}"); + app.view_mut().unwrap().outline = true; + let (covers, papers, edges, names) = canvas_look(&mut app, &ctx); + assert_eq!(covers.last(), Some(&Color32::WHITE), "{case}: the canvas is white in Outline"); + assert!(!covers.contains(&pasteboard), "{case}: no pasteboard in Outline"); + assert!(papers.is_empty(), "{case}: no paper over the artboards in Outline: {papers:?}"); + assert_eq!(edges, 2, "{case}: the artboards show as their edges"); + assert_eq!(names, [OUTLINE_DIM; 2], "{case}: names readable on white"); + } + } + } +} + +/// In Outline the canvas stays white with Simulate Colored Paper on, with an artboard's own +/// background color, and with View › Hide Artboards, which in Preview show the paper color, the +/// artboard's color and the paper color over the whole canvas. +#[test] +fn outline_draws_no_colored_paper() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.session.execute("file.new", &json!({"width": 200, "height": 100, "artboards": 2})).unwrap(); + { + let doc = std::sync::Arc::make_mut(&mut app.session.active_mut().unwrap().doc); + doc.setup.simulate_paper = true; + doc.setup.grid_colors = [vectorcraft_color::Color::rgb(0.9, 0.8, 0.6), vectorcraft_color::Color::rgb(0.5, 0.5, 0.5)]; + doc.artboards[1].color = Some(vectorcraft_color::Color::rgb(0.6, 0.8, 1.0)); + } + let paper = crate::panels::c32(&app.session.active().unwrap().doc.setup.paper()); + let ctx = egui::Context::default(); + crate::theme::apply(&ctx, crate::theme::Brightness::Dark); + app.view_mut().unwrap().outline = false; + let (_, papers, _, _) = canvas_look(&mut app, &ctx); + assert_eq!(papers.len(), 2); + assert_eq!(papers[0], paper, "Preview: the simulated paper"); + assert_ne!(papers[1], paper, "Preview: the artboard's own color"); + app.view_mut().unwrap().outline = true; + let (covers, papers, edges, _) = canvas_look(&mut app, &ctx); + assert_eq!(covers.last(), Some(&Color32::WHITE)); + assert!(papers.is_empty(), "{papers:?}"); + assert_eq!(edges, 2); + app.ui.view.artboards = false; + app.view_mut().unwrap().outline = false; + let (covers, _, edges, _) = canvas_look(&mut app, &ctx); + assert_eq!(covers.last(), Some(&paper), "Preview with Hide Artboards: the paper over the whole canvas"); + assert_eq!(edges, 0); + app.view_mut().unwrap().outline = true; + let (covers, papers, edges, _) = canvas_look(&mut app, &ctx); + assert_eq!(covers.last(), Some(&Color32::WHITE), "Outline with Hide Artboards"); + assert!(!covers.contains(&paper)); + assert!(papers.is_empty()); + assert_eq!(edges, 0); +} + +/// A split-view pane or floating window draws its own view's Outline, whatever the current view +/// shows: the white canvas and dark gray artboard names in Outline, and the pasteboard and the +/// theme's names in Preview. +#[test] +fn a_pane_draws_its_own_views_outline() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 200, "height": 100, "artboards": 2})).unwrap(); + crate::doc_windows::new_window(&mut app).unwrap(); + let ctx = egui::Context::default(); + crate::theme::apply(&ctx, crate::theme::Brightness::Dark); + let t = Tokens::get(&ctx); + let other = (0, 1); + for pane_outline in [true, false] { + crate::doc_windows::view_mut(&mut app, other).unwrap().outline = pane_outline; + app.view_mut().unwrap().outline = !pane_outline; + let cell = egui::Rect::from_min_size(pos2(0.0, 0.0), vec2(600.0, 400.0)); + let raw = egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(Pos2::ZERO, vec2(800.0, 600.0))), ..Default::default() }; + let mut out = ctx.run_ui(raw, |ui| { + panes::pane(&mut app, ui, other, cell); + }); + out.textures_delta.clear(); + let mut s = vec![]; + fn flat(s: Shape, out: &mut Vec) { + match s { + Shape::Vec(v) => v.into_iter().for_each(|s| flat(s, out)), + s => out.push(s), + } + } + out.shapes.into_iter().for_each(|c| flat(c.shape, &mut s)); + let fills: Vec = s.iter().filter_map(|s| if let Shape::Rect(r) = s { Some(r.fill) } else { None }).collect(); + let names: Vec = s + .iter() + .filter_map(|s| if let Shape::Text(x) = s { names_an_artboard(x.galley.text()).then_some(x.fallback_color) } else { None }) + .collect(); + let (canvas, name) = if pane_outline { (Color32::WHITE, OUTLINE_DIM) } else { (t.pasteboard, t.text_dim) }; + assert_eq!(fills.first(), Some(&canvas), "pane in Outline: {pane_outline}"); + assert_eq!(names, [name; 2], "pane in Outline: {pane_outline}"); + } +} + +/// While the rulers' origin is dragged out of their corner, its crosshair draws over the canvas in +/// the theme's dim text color in Preview, and in Outline in the dark gray that shows on the white +/// canvas. +#[test] +fn the_ruler_origin_crosshair_shows_on_the_outline_canvas() { + use egui::Event; + for outline in [false, true] { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); + app.ui.view.rulers = true; + app.view_mut().unwrap().outline = outline; + let ctx = egui::Context::default(); + crate::theme::apply(&ctx, crate::theme::Brightness::Dark); + frame(&mut app, &ctx, vec![]); + frame(&mut app, &ctx, vec![]); + let rect = app.canvas_rect.unwrap(); + let corner = pos2(rect.left() - RULER / 2.0, rect.top() - RULER / 2.0); + let to = rect.center(); + let button = |pos, pressed| Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() }; + frame(&mut app, &ctx, vec![Event::PointerMoved(corner)]); + frame(&mut app, &ctx, vec![button(corner, true)]); + frame(&mut app, &ctx, vec![Event::PointerMoved(to)]); + let (s, mut delta) = frame_output(&mut app, &ctx); + delta.clear(); + let lines: Vec = s + .iter() + .filter_map(|s| match s { + Shape::LineSegment { points, stroke } + if (points[0].x - to.x).abs() < 1.5 + && (points[1].x - to.x).abs() < 1.5 + && points[0].y <= rect.top() + 1.0 + && points[1].y >= rect.bottom() - 1.0 => + { + Some(stroke.color) + } + _ => None, + }) + .collect(); + let want = if outline { OUTLINE_DIM } else { Tokens::get(&ctx).text_dim }; + assert_eq!(lines, [want], "Outline: {outline}"); + frame(&mut app, &ctx, vec![button(to, false)]); + } +} + /// #3797: a preferences file saved while View › Outline was an interface setting still loads, with /// its other view settings, and its Outline value does not put a document in Outline. #[test] diff --git a/crates/ui-egui/src/canvas/view.rs b/crates/ui-egui/src/canvas/view.rs index 558bf011d9..60cb6687b4 100644 --- a/crates/ui-egui/src/canvas/view.rs +++ b/crates/ui-egui/src/canvas/view.rs @@ -1,6 +1,16 @@ use super::drag::{drag_id, drop_press}; use super::{CornerRadius, Drag, Point, Pos2, Rect, SCROLL_BAR, Sense, Stroke, Tokens, Ui, VectorcraftApp, View, Xf, pos2, vec2}; +/// The mouse and control-channel Rotate View gestures use the same angle and Shift snapping. +pub(crate) fn drag_rotation(center: Pos2, point: Pos2, start_angle: f64, start_rotation: f64, snap: bool) -> f64 { + let angle = (point.y - center.y).atan2(point.x - center.x) as f64; + let mut degrees = start_rotation + (angle - start_angle).to_degrees(); + if snap { + degrees = (degrees / 15.0).round() * 15.0; + } + vectorcraft_geom::normalize_deg(degrees) +} + /// Fit the view (View → Fit Artboard / Fit All / Actual Size, Arrange Tools › Zoom to Selection). pub fn fit(app: &mut VectorcraftApp, how: &str) { let Some(rect) = app.canvas_rect else { diff --git a/crates/ui-egui/src/chrome/status_bar.rs b/crates/ui-egui/src/chrome/status_bar.rs index 9fbd02327b..8995080215 100644 --- a/crates/ui-egui/src/chrome/status_bar.rs +++ b/crates/ui-egui/src/chrome/status_bar.rs @@ -179,12 +179,18 @@ pub(super) fn status_readouts(app: &VectorcraftApp, ui: &mut Ui, t: &Tokens) { } right = left - gap; } - let busy: Vec<&str> = app - .background - .jobs - .iter() - .filter(|j| !j.label.is_empty() && !j.cancelled()) - .map(|j| j.label.as_str()) + let script = app.session.script_running().then_some("Running a script"); + if script.is_some() { + let left = (right - 52.0).max(area.left()); + let stop = egui::Rect::from_min_max(egui::pos2(left, area.top() + 1.0), egui::pos2(right, area.bottom() - 1.0)); + if ui.put(stop, egui::Button::new(tl!("Stop")).small()).clicked() { + app.session.script_interrupt().set(); + } + right = left - gap; + } + let busy: Vec<&str> = script + .into_iter() + .chain(app.background.jobs.iter().filter(|j| !j.label.is_empty() && !j.cancelled()).map(|j| j.label.as_str())) .chain(app.opening.pending.iter().map(|p| p.label.as_str())) .chain(app.placing.pending.iter().map(|p| p.label.as_str())) .collect(); diff --git a/crates/ui-egui/src/control.rs b/crates/ui-egui/src/control.rs index 6af51d95a3..419d4ab903 100644 --- a/crates/ui-egui/src/control.rs +++ b/crates/ui-egui/src/control.rs @@ -234,6 +234,8 @@ pub fn inspect(app: &VectorcraftApp, ctx: &egui::Context) -> Value { fields.remove("floating_panels"); } json!({ + "scriptRunning": app.session.script_running(), + "scriptReport": app.session.script_report(), "tool": app.session.tool_id(), "toolOptions": app.session.tool_options(), "ui": ui, @@ -608,10 +610,116 @@ pub(crate) fn save_screenshot_with_limit( #[cfg(test)] mod tests; +/// The window and coordinate mapping where a control-channel Rotate View drag began. +#[derive(Clone, Copy)] +pub(crate) struct RotateViewPress { + window: (u64, u32), + document_resets: u64, + xf: Xf, + start_angle: f64, + start_rotation: f64, +} + +/// Rotate View belongs to the canvas, not the engine's placeholder tool. Keep its press mapping +/// across requests so document-coordinate drags do not move again as the view turns underneath. +fn rotate_view_pointer( + app: &mut VectorcraftApp, + kind: PointerKind, + position: vectorcraft_geom::Point, + screen: bool, + shift: bool, +) -> Result<(), String> { + let window = app.session.active().zip(crate::doc_windows::current(app)).map(|(d, w)| (d.uid, w.1)).ok_or("no document")?; + let document_resets = app.session.tool_resets(); + let stored = if kind == PointerKind::Down { None } else { app.control_rotate_press }; + if kind == PointerKind::Drag && stored.is_none() { + return Err("Rotate View needs a down event before a drag".into()); + } + let mut press = match stored { + Some(press) => press, + None => { + let rect = app.canvas_rect.ok_or("no canvas yet")?; + let view = app.view().ok_or("no document")?; + RotateViewPress { window, document_resets, xf: Xf::new(rect, view), start_angle: 0.0, start_rotation: view.rotation } + } + }; + // A gesture cannot turn a different document/view or resume after its document was reset. + if (press.window, press.document_resets) != (window, document_resets) { + return Err("the Rotate View gesture's window or document changed".into()); + } + let point = if screen { egui::pos2(position.x as f32, position.y as f32) } else { press.xf.to_screen(position) }; + let center = press.xf.rect.center(); + if !point.is_finite() || !center.is_finite() { + return Err("Rotate View needs finite canvas coordinates".into()); + } + match kind { + PointerKind::Down => { + press.start_angle = (point.y - center.y).atan2(point.x - center.x) as f64; + app.control_rotate_press = Some(press); + } + PointerKind::Drag => { + app.view_mut().ok_or("no document")?.rotation = + crate::canvas::drag_rotation(center, point, press.start_angle, press.start_rotation, shift); + } + PointerKind::Up => { + app.control_rotate_press = None; + } + PointerKind::Move | PointerKind::DoubleClick => {} + } + Ok(()) +} + +/// A Rotate View packet accepts only the documented boolean modifier fields. +fn validate_rotate_view_mods(value: Option<&Value>) -> Result<(), String> { + let Some(value) = value else { return Ok(()) }; + let Some(fields) = value.as_object() else { return Err("Rotate View `mods` must be an object of booleans".into()) }; + if fields.iter().any(|(key, value)| !matches!(key.as_str(), "shift" | "alt" | "cmd" | "ctrl" | "space") || !value.is_boolean()) { + return Err("Rotate View `mods` accepts only boolean shift, alt, cmd, ctrl and space".into()); + } + Ok(()) +} + +/// Reject malformed coordinates and modifiers before any event can change the angle or press. +fn validate_rotate_view_events(params: &Value, events: &[Value]) -> Result<(), String> { + validate_rotate_view_mods(params.get("mods"))?; + for event in events { + for axis in ["x", "y"] { + if event.get(axis).and_then(Value::as_f64).filter(|value| value.is_finite()).is_none() { + return Err(format!("Rotate View `{axis}` must be a finite number")); + } + } + validate_rotate_view_mods(event.get("mods"))?; + if event.get("space").is_some_and(|space| !matches!(space.as_str(), Some("doc" | "screen"))) { + return Err("Rotate View `space` must be doc or screen".into()); + } + } + Ok(()) +} + /// `ui.pointer`: pointer events through the tools. fn pointer_events(app: &mut VectorcraftApp, ctx: &egui::Context, req: &ControlRequest) -> Outcome { + let rotating = app.session.tool_id() == "rotateView"; + let before = if rotating { app.view().map(|view| view.rotation) } else { None }; + let outcome = pointer_events_inner(app, ctx, req); + if rotating && matches!(&outcome, Outcome::Done(reply) if reply.get("ok").and_then(Value::as_bool) == Some(false)) { + // A failed packet must neither leave a partial turn nor allow a later drag to resume it. + app.control_rotate_press = None; + if let (Some(before), Some(view)) = (before, app.view_mut()) { + view.rotation = before; + } + ctx.request_repaint(); + } + outcome +} + +/// Apply a pointer packet after Rotate View validation; other tools retain their existing routing. +fn pointer_events_inner(app: &mut VectorcraftApp, ctx: &egui::Context, req: &ControlRequest) -> Outcome { let p = &req.params; let Some(events) = p.get("events").and_then(Value::as_array) else { return err("missing `events`") }; + let rotating = app.session.tool_id() == "rotateView"; + if rotating && let Err(error) = validate_rotate_view_events(p, events) { + return err(error); + } let base_mods: Mods = p.get("mods").and_then(|m| serde_json::from_value(m.clone()).ok()).unwrap_or_default(); let view = app.view_info(); let xf = app.canvas_rect.zip(app.view().copied()).map(|(rect, v)| Xf::new(rect, &v)); @@ -634,6 +742,13 @@ fn pointer_events(app: &mut VectorcraftApp, ctx: &egui::Context, req: &ControlRe let x = e.get("x").and_then(Value::as_f64).unwrap_or(0.0); let y = e.get("y").and_then(Value::as_f64).unwrap_or(0.0); let screen = e.get("space").and_then(Value::as_str) == Some("screen"); + let mods = e.get("mods").and_then(|m| serde_json::from_value(m.clone()).ok()).unwrap_or(base_mods); + if rotating { + if let Err(e) = rotate_view_pointer(app, kind, vectorcraft_geom::Point::new(x, y), screen, mods.shift) { + return err(e); + } + continue; + } let pos = if screen { match xf { Some(xf) => xf.to_doc(egui::pos2(x as f32, y as f32)), @@ -642,7 +757,6 @@ fn pointer_events(app: &mut VectorcraftApp, ctx: &egui::Context, req: &ControlRe } else { vectorcraft_geom::Point::new(x, y) }; - let mods = e.get("mods").and_then(|m| serde_json::from_value(m.clone()).ok()).unwrap_or(base_mods); // A tilt given in screen axes leans the same way on the page as on the screen. let pen = PointerEvent::json_pen(e).map(|q| match xf { Some(xf) if screen => crate::canvas::pose_on_page(q, &xf), diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index 9137442f04..fd0373b72b 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -109,6 +109,7 @@ pub mod save_style_library; pub mod save_swatch_library; pub mod save_symbol_library; pub mod script_check; +pub mod script_run; pub mod shape_builder_options; pub(crate) mod shapes; pub mod shortcut_import; @@ -404,6 +405,9 @@ registry! { PluginImport: [plugin::IMPORT_KIND] => plugin::IMPORT_SPEC, PluginInstall: [plugin::INSTALL_KIND] => plugin::INSTALL_SPEC, ScriptCheck: [script_check::KIND] => script_check::SPEC, + ScriptRun: [script_run::KIND] => script_run::SPEC, + ScriptGrowth: [script_run::GROWTH_KIND] => script_run::GROWTH_SPEC, + ScriptClose: [script_run::CLOSE_KIND] => script_run::CLOSE_SPEC, VectorHalftone: [halftone::KIND] => halftone::SPEC, SimplifySlider: [simplify_slider::KIND] => simplify_slider::SPEC, SmoothSlider: [smooth_slider::KIND] => smooth_slider::SPEC, @@ -574,6 +578,10 @@ pub fn cancel(app: &mut VectorcraftApp) { if d.kind == safe_mode::STOPPED { safe_mode::cancel_stopped(app); } + // The growth question's Cancel button is its Stop button. + if d.kind == script_run::GROWTH_KIND { + app.session.script_request_stop(); + } // Toolbar-only Flare options start no preview and must not cancel a gesture // that was already active before opening them. The generic parameter dialog has a spec // without a preview, yet previews some commands (Grid Repeat Options) when asked to. diff --git a/crates/ui-egui/src/dialogs/script_run.rs b/crates/ui-egui/src/dialogs/script_run.rs new file mode 100644 index 0000000000..2ef43cb8fe --- /dev/null +++ b/crates/ui-egui/src/dialogs/script_run.rs @@ -0,0 +1,147 @@ +//! File › Scripts › Other Script…: choosing a JavaScript file and the warning before it runs +//! (`script.run` runs it), the question a run that keeps adding art asks, and the question quitting +//! asks while a script runs. +//! +//! `ui.runScript {path? | source?, name?}` shows the warning for that script; without either it +//! asks for a `.js` or `.jsx` file (the web opens the browser's file picker). With Preferences › +//! General › Show External Script Warning off, the chosen script runs at once. Warning fields: +//! `name`, `script` (`script.run`'s params) and `dontShow` (true: turn the warning off). + +use serde_json::{Value, json}; +use vectorcraft_engine::cmd::scripts::{RUN_EXTS, TOO_LARGE, runs}; + +use super::DialogSpec; +use crate::state::Dialog; +use crate::theme::{self, Tokens}; +use crate::{FilePick, VectorcraftApp, widgets}; + +/// The dialog kind of the warning before a script runs. +pub const KIND: &str = "scriptRun"; +/// The dialog kind of the question a run asks when it has added a great deal. +pub const GROWTH_KIND: &str = "scriptGrowth"; +/// The dialog kind of the question quitting asks while a script runs. +pub const CLOSE_KIND: &str = "scriptClose"; + +pub(super) const SPEC: DialogSpec = DialogSpec { + heading: |_| tl!("Run Script").into(), + body, + confirm, + ok: Some("Run"), + min_width: 420.0, + max_width: Some(520.0), + ..DialogSpec::FORM +}; + +pub(super) const GROWTH_SPEC: DialogSpec = DialogSpec { + heading: |_| tl!("A Script Is Running").into(), + body: |_, ui, _| { + ui.label(tl!("This script has added a great many objects. Continue, or stop it and undo what it did?")); + false + }, + confirm: growth_confirm, + ok: Some("Continue"), + cancel: Some("Stop"), + min_width: 420.0, + max_width: Some(520.0), + ..DialogSpec::FORM +}; + +pub(super) const CLOSE_SPEC: DialogSpec = DialogSpec { + heading: |_| tl!("A Script Is Running").into(), + body: |_, ui, _| { + ui.label(tl!("Stop the script and undo what it did? Then quit again.")); + false + }, + confirm: close_confirm, + ok: Some("Stop"), + min_width: 420.0, + max_width: Some(520.0), + ..DialogSpec::FORM +}; + +/// A file the web's picker delivered: its name and bytes, or `None` for a file over +/// [`vectorcraft_engine::script::MAX_SOURCE_BYTES`], which is not read. +pub type ScriptInbox = std::sync::Arc>)>>>; + +/// Shows the warning for the next script the web's picker delivered, once no dialog is open. A +/// picker that was canceled delivers nothing. +pub(crate) fn drain(app: &mut VectorcraftApp) { + if app.ui.dialog.is_some() { + return; + } + let Some((name, bytes)) = app.services.script_inbox.as_ref().and_then(|q| q.lock().unwrap_or_else(|e| e.into_inner()).pop()) else { return }; + let result = match bytes.as_deref().map(std::str::from_utf8) { + None => Err(TOO_LARGE.to_string()), + Some(Ok(source)) => chosen(app, json!({"source": source, "name": name})), + Some(Err(_)) => Err("the script is not UTF-8 text".to_string()), + }; + if let Err(e) = result { + app.status(e); + } +} + +/// `ui.runScript`: the script at `path` or given as `source`; without either, pick a file. +pub(crate) fn command(app: &mut VectorcraftApp, p: &Value) -> Result { + if p.get("path").is_some() || p.get("source").is_some() { + return chosen(app, p.clone()); + } + if let Some(pick) = app.services.script_async.as_mut() { + pick(); + return Ok(Value::Null); + } + let pick = FilePick { filters: vec![FilePick::filter("Scripts", RUN_EXTS)], ..Default::default() }; + let path = crate::picks::open(app, &pick).ok_or("cancelled")?; + chosen(app, json!({ "path": path })) +} + +/// A script was chosen: `params` are `script.run`'s. It runs after the warning, when that is on. +pub(crate) fn chosen(app: &mut VectorcraftApp, params: Value) -> Result { + let path = params.get("path").and_then(Value::as_str); + if path.is_some_and(|path| !runs(path)) { + return Err("Choose a .js or .jsx script".into()); + } + if !app.session.prefs.show_external_script_warning { + return app.run("script.run", params); + } + let name = params.get("name").and_then(Value::as_str).or(path).map_or_else(|| "script".to_string(), vectorcraft_engine::cmd::fileio::file_name); + app.ui.dialog = Some(Dialog::new(KIND, json!({"name": name, "script": params, "dontShow": false}))); + Ok(Value::Null) +} + +fn body(_: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { + let t = Tokens::get(ui.ctx()); + ui.label(egui::RichText::new(d.fields.get("name").and_then(Value::as_str).unwrap_or_default()).font(theme::semibold(12.5)).color(t.text_strong)); + ui.add_space(4.0); + ui.label(tl!("A script can change the open documents and can write files through the commands it runs. Run only scripts you trust.")); + ui.add_space(8.0); + let dont_show = d.fields.get("dontShow").and_then(Value::as_bool).unwrap_or(false); + if widgets::check(ui, tl!("Do not show this warning again"), dont_show, true) { + d.fields.insert("dontShow".into(), json!(!dont_show)); + } + false +} + +fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result { + if d.fields.get("dontShow").and_then(Value::as_bool).unwrap_or(false) { + app.run("prefs.set", json!({"key": "showExternalScriptWarning", "value": false}))?; + } + let script = d.fields.get("script").cloned().unwrap_or(Value::Null); + app.ui.dialog = None; + app.run("script.run", script) +} + +fn growth_confirm(app: &mut VectorcraftApp, _: &Dialog) -> Result { + app.ui.dialog = None; + app.session.script_continue(); + Ok(Value::Null) +} + +fn close_confirm(app: &mut VectorcraftApp, _: &Dialog) -> Result { + app.ui.dialog = None; + if app.session.script_abandon() { + let error = app.session.script_failure_text().unwrap_or_default(); + crate::script_runs::failed(app, error); + app.sync_views(); + } + Ok(Value::Null) +} diff --git a/crates/ui-egui/src/i18n/bg.tsv b/crates/ui-egui/src/i18n/bg.tsv index 05ba6858f8..4cd16b1cff 100644 --- a/crates/ui-egui/src/i18n/bg.tsv +++ b/crates/ui-egui/src/i18n/bg.tsv @@ -3052,6 +3052,13 @@ digits Malayalam Малаялам Settings… Настройки… Setup… Настройка… Shadows and Glows Сенки и блясъци + Game HUD Игрови HUD + Health Fill Здраве + Mana Glow Мана + Damage Flash Щета + Quest Outline Квест + Coin Shine Монета + Boss Alert Бос Shape Фигура Shape Builder Създател на фигури Shape Builder Regions Области на създателя на фигури @@ -3954,6 +3961,15 @@ axis Both И двете @msg Combine Slices: the slices have no bounds Обединяване на парчета: парчетата нямат граници @msg Convert to Artboards: selection has no area Преобразуване в работни области: селекцията няма площ @msg Convert to Shape: no rectangles or ellipses selected Преобразуване в фигура: няма избрани правоъгълници или елипси + Run Изпълни + Run Script Изпълни скрипт + Stop Script Спри скрипта + Show External Script Warning Показвай предупреждение за външни скриптове + A Script Is Running Изпълнява се скрипт + 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 Не показвай повече това предупреждение + Stop the script and undo what it did? Then quit again. Да се спре ли скриптът и да се отменят ли промените му? След това излезте отново. + This script has added a great many objects. Continue, or stop it and undo what it did? Този скрипт добави изключително много обекти. Да продължи ли, или да се спре и да се отменят промените му? @msg Copied the script report Копиран е отчетът за скрипта @msg Corners edits the corners of a path Ъглите редактират ъглите на пътя @msg Couldn't copy to the system clipboard: {e} Неуспешно копиране в системния клипборд: {e} @@ -5835,6 +5851,11 @@ axis Y Axis Y ос Button Бутон Panel Панел UI Frames UI рамки + Map Markers Маркери на карта + Pin Карфица + Flag Флаг + Crosshair Мерник + Checkpoint Контролна точка Open Symbol Library Отваряне на библиотека със символи Save Symbol Library Запазване на библиотека със символи Save Symbol Library… Запази библиотека със символи… diff --git a/crates/ui-egui/src/i18n/bs.tsv b/crates/ui-egui/src/i18n/bs.tsv index eb96edd5f8..a5491ad0cc 100644 --- a/crates/ui-egui/src/i18n/bs.tsv +++ b/crates/ui-egui/src/i18n/bs.tsv @@ -766,6 +766,13 @@ Other Library… Druga biblioteka… Graphic Style Libraries Biblioteke grafičkih stilova Shadows and Glows Sjene i sjajevi + Game HUD Igraći HUD + Health Fill Zdravlje + Mana Glow Mana + Damage Flash Šteta + Quest Outline Zadatak + Coin Shine Novčić + Boss Alert Bos Outlines and Rules Obrisi i linije Hand-Drawn Ručno crtano Gradient Finishes Gradijentne završnice @@ -4319,6 +4326,15 @@ imageTrace Outline Obris @msg Combine Slices: the slices have no bounds Kombinuj isječke: isječci nemaju granice @msg Convert to Artboards: selection has no area Pretvori u radne ploče: odabir nema površinu @msg Convert to Shape: no rectangles or ellipses selected Pretvori u oblik: nisu odabrani pravougaonici ni elipse + Run Pokreni + Run Script Pokreni skriptu + Stop Script Zaustavi skriptu + Show External Script Warning Prikaži upozorenje za vanjske skripte + A Script Is Running Skripta se izvršava + 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 + Stop the script and undo what it did? Then quit again. Zaustaviti skriptu i poništiti ono što je uradila? Zatim ponovo izađite. + This script has added a great many objects. Continue, or stop it and undo what it did? Ova skripta je dodala veoma mnogo objekata. Nastaviti, ili je zaustaviti i poništiti ono što je uradila? @msg Copied the script report Izvještaj skripte kopiran @msg Corners edits the corners of a path Uglovi uređuje uglove putanje @msg Couldn't copy to the system clipboard: {e} Nije moguće kopirati u sistemski međuspremnik: {e} @@ -5879,6 +5895,11 @@ axis Y Axis Y osa Button Dugme Panel Panel UI Frames UI okviri + Map Markers Markeri mape + Pin Pin + Flag Zastava + Crosshair Nišan + Checkpoint Kontrolna tačka Open Symbol Library Otvori biblioteku simbola Save Symbol Library Sačuvaj biblioteku simbola Save Symbol Library… Sačuvaj biblioteku simbola… diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index cad8f83d4a..22ffad50fa 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -443,6 +443,11 @@ antiAlias Sharp Nítid Button Botó Panel Panell UI Frames Marcs d’IU + Map Markers Marcadors de mapa + Pin Xinxeta + Flag Bandera + Crosshair Punt de mira + Checkpoint Punt de control Batch Lot Batch… Lot… Bearing Orientació @@ -3921,6 +3926,13 @@ digits Malayalam Malaiàlam Shading Sombra Shadow Intensity Intensitat de l’ombra Shadows and Glows Ombres i resplendors + Game HUD HUD de joc + Health Fill Salut + Mana Glow Mana + Damage Flash Dany + Quest Outline Missió + Coin Shine Moneda + Boss Alert Cap Shape Forma Shape Builder Constructor de formes Shape Builder Delete Suprimeix del constructor de formes @@ -5154,6 +5166,28 @@ digits Malayalam Malaiàlam @msg control must be fillStroke, coloring, drawMode or screenMode control ha de ser fillStroke, coloring, drawMode o screenMode @msg Convert to Artboards: selection has no area Converteix en taulers: la selecció no té àrea @msg Convert to Shape: no rectangles or ellipses selected Converteix en forma: no s’ha seleccionat cap rectangle ni el·lipse + Run Executa + Run Script Executa l'script + Stop Script Atura l'script + Show External Script Warning Mostra l'avís dels scripts externs + A Script Is Running S'està executant un script + 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 + Stop the script and undo what it did? Then quit again. Voleu aturar l'script i desfer el que ha fet? Després, torneu a sortir. + This script has added a great many objects. Continue, or stop it and undo what it did? Aquest script ha afegit moltíssims objectes. Voleu continuar, o aturar-lo i desfer el que ha fet? +@msg Choose a .js or .jsx script Trieu un script .js o .jsx +@msg Ran {name} S'ha executat {name} +@msg The script was stopped and its changes were undone L'script s'ha aturat i s'han desfet els seus canvis +@msg a script is running: stop it or wait for it to finish s'està executant un script: atureu-lo o espereu que acabi +@msg this is a compiled script, which cannot be run; use its source text aquest és un script compilat, que no es pot executar; useu el seu text font +@msg the script is not UTF-8 text l'script no és text UTF-8 +@msg the script is too large to run l'script és massa gran per executar-lo +@msg a drag or an undo group is open; finish it before running a script hi ha un arrossegament o un grup de desfer obert; acabeu-lo abans d'executar un script +@msg the script left a document that cannot be kept l'script ha deixat un document que no es pot conservar +@msg the script's run is no longer available l'execució de l'script ja no està disponible +@msg a failed command changed undo steps that could not be put back, so the script was stopped una ordre fallida ha canviat passos de desfer que no s'han pogut restaurar, així que l'script s'ha aturat +@msg a recovery copy could not be written, so the script was not run no s'ha pogut escriure una còpia de recuperació, per tant l'script no s'ha executat +@msg Running a script S'està executant un script @msg Copied the script report S’ha copiat l’informe de l’script @msg Corners edits the corners of a path Cantonades edita les cantonades d’un traçat @msg could not decode image: {0} no s’ha pogut descodificar la imatge: {0} diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index e494c36668..3829dc8d41 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -775,6 +775,13 @@ Other Library… Jiná knihovna… Graphic Style Libraries Knihovny grafických stylů Shadows and Glows Stíny a záře + Game HUD Herní HUD + Health Fill Život + Mana Glow Mana + Damage Flash Poškození + Quest Outline Úkol + Coin Shine Mince + Boss Alert Boss Outlines and Rules Obrysy a linky Hand-Drawn Ručně kreslené Gradient Finishes Přechodové povrchy @@ -4377,6 +4384,28 @@ imageTrace Outline Obrys @msg Combine Slices: the slices have no bounds Spojit řezy: řezy nemají hranice @msg Convert to Artboards: selection has no area Převést na pracovní plochy: výběr nemá žádnou plochu @msg Convert to Shape: no rectangles or ellipses selected Převést na tvar: nejsou vybrány žádné obdélníky ani elipsy + Run Spustit + Run Script Spustit skript + Stop Script Zastavit skript + Show External Script Warning Zobrazit upozornění u externích skriptů + A Script Is Running Běží skript + 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 + Stop the script and undo what it did? Then quit again. Zastavit skript a vrátit jeho změny? Potom aplikaci ukončete znovu. + This script has added a great many objects. Continue, or stop it and undo what it did? Tento skript přidal velmi mnoho objektů. Pokračovat, nebo jej zastavit a vrátit jeho změny? +@msg Choose a .js or .jsx script Vyberte skript .js nebo .jsx +@msg Ran {name} Spuštěno: {name} +@msg The script was stopped and its changes were undone Skript byl zastaven a jeho změny byly vráceny +@msg a script is running: stop it or wait for it to finish běží skript: zastavte jej nebo počkejte na jeho dokončení +@msg this is a compiled script, which cannot be run; use its source text toto je zkompilovaný skript, který nelze spustit; použijte jeho zdrojový text +@msg the script is not UTF-8 text skript není text v kódování UTF-8 +@msg the script is too large to run skript je příliš velký na spuštění +@msg a drag or an undo group is open; finish it before running a script je otevřené tažení nebo skupina kroků zpět; před spuštěním skriptu ji dokončete +@msg the script left a document that cannot be kept skript zanechal dokument, který nelze zachovat +@msg the script's run is no longer available běh skriptu již není k dispozici +@msg a failed command changed undo steps that could not be put back, so the script was stopped neúspěšný příkaz změnil kroky zpět, které nebylo možné obnovit, proto byl skript zastaven +@msg a recovery copy could not be written, so the script was not run záložní kopii se nepodařilo zapsat, proto skript nebyl spuštěn +@msg Running a script Běží skript @msg Copied the script report Zpráva o skriptu zkopírována @msg Corners edits the corners of a path Rohy upravuje rohy cesty @msg Couldn't copy to the system clipboard: {e} Nelze kopírovat do systémové schránky: {e} @@ -6030,6 +6059,11 @@ axis Y Axis osa Y Button Tlačítko Panel Panel UI Frames Rámce UI + Map Markers Mapové značky + Pin Špendlík + Flag Vlajka + Crosshair Zaměřovač + Checkpoint Kontrolní bod Open Symbol Library Otevřít knihovnu symbolů Save Symbol Library Uložit knihovnu symbolů Save Symbol Library… Uložit knihovnu symbolů… diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index 9cf36f69f5..52257905f0 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -712,6 +712,13 @@ Other Library… Andet bibliotek… Graphic Style Libraries Biblioteker med grafiske stile Shadows and Glows Skygger og gløder + Game HUD Spil-HUD + Health Fill Helbred + Mana Glow Mana + Damage Flash Skade + Quest Outline Quest + Coin Shine Mønt + Boss Alert Boss Outlines and Rules Konturer og linjer Hand-Drawn Håndtegnet Gradient Finishes Gradientfinish @@ -4073,6 +4080,15 @@ imageTrace Outline Kontur @msg Combine Slices: the slices have no bounds Kombinér udsnit: udsnittene har ingen grænser @msg Convert to Artboards: selection has no area Konvertér til tegneflader: markeringen har intet areal @msg Convert to Shape: no rectangles or ellipses selected Konvertér til figur: ingen rektangler eller ellipser er markeret + Run Kør + Run Script Kør script + Stop Script Stop script + Show External Script Warning Vis advarsel om eksterne scripts + A Script Is Running Et script kører + 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 + Stop the script and undo what it did? Then quit again. Stop scriptet og fortryd det, det har gjort? Afslut derefter igen. + This script has added a great many objects. Continue, or stop it and undo what it did? Dette script har tilføjet rigtig mange objekter. Fortsæt, eller stop det og fortryd det, det har gjort? @msg Copied the script report Kopierede scriptrapporten @msg Corners edits the corners of a path Hjørner redigerer hjørnerne på en kurve @msg Couldn't copy to the system clipboard: {e} Kunne ikke kopiere til systemets udklipsholder: {e} @@ -5850,6 +5866,11 @@ axis Y Axis Y-akse Button Knap Panel Panel UI Frames UI-rammer + Map Markers Kortmarkører + Pin Nål + Flag Flag + Crosshair Sigtekorn + Checkpoint Kontrolpunkt Open Symbol Library Åbn symbolbibliotek Save Symbol Library Gem symbolbibliotek Save Symbol Library… Gem symbolbibliotek… diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index 740231edd7..9c64185d36 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -3099,6 +3099,13 @@ digits Malayalam Malayalam Settings… Einstellungen… Setup… Einrichten… Shadows and Glows Schatten und Leuchteffekte + Game HUD Spiel-HUD + Health Fill Leben + Mana Glow Mana + Damage Flash Schaden + Quest Outline Quest + Coin Shine Münze + Boss Alert Boss Shape Form Shape Builder Formerstellung Shape Builder Regions Formerstellungsbereiche @@ -3982,6 +3989,28 @@ theme Appearance Erscheinungsbild @msg Combine Slices: the slices have no bounds Slices kombinieren: Die Slices haben keine Begrenzung @msg Convert to Artboards: selection has no area In Zeichenflächen umwandeln: Die Auswahl hat keine Fläche @msg Convert to Shape: no rectangles or ellipses selected In Form umwandeln: keine Rechtecke oder Ellipsen ausgewählt + Run Ausführen + Run Script Skript ausführen + Stop Script Skript stoppen + Show External Script Warning Warnung bei externen Skripten anzeigen + A Script Is Running Ein Skript wird ausgeführt + 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 + Stop the script and undo what it did? Then quit again. Skript stoppen und seine Änderungen rückgängig machen? Beenden Sie danach erneut. + This script has added a great many objects. Continue, or stop it and undo what it did? Dieses Skript hat sehr viele Objekte hinzugefügt. Fortfahren oder das Skript stoppen und seine Änderungen rückgängig machen? +@msg Choose a .js or .jsx script Wählen Sie ein .js- oder .jsx-Skript +@msg Ran {name} {name} ausgeführt +@msg The script was stopped and its changes were undone Das Skript wurde gestoppt und seine Änderungen wurden rückgängig gemacht +@msg a script is running: stop it or wait for it to finish ein Skript wird ausgeführt: stoppen Sie es oder warten Sie, bis es fertig ist +@msg this is a compiled script, which cannot be run; use its source text dies ist ein kompiliertes Skript, das nicht ausgeführt werden kann; verwenden Sie seinen Quelltext +@msg the script is not UTF-8 text das Skript ist kein UTF-8-Text +@msg the script is too large to run das Skript ist zu groß zum Ausführen +@msg a drag or an undo group is open; finish it before running a script ein Ziehvorgang oder eine Rückgängig-Gruppe ist offen; schließen Sie sie ab, bevor Sie ein Skript ausführen +@msg the script left a document that cannot be kept das Skript hat ein Dokument hinterlassen, das nicht behalten werden kann +@msg the script's run is no longer available der Lauf des Skripts ist nicht mehr verfügbar +@msg a failed command changed undo steps that could not be put back, so the script was stopped ein fehlgeschlagener Befehl hat Rückgängig-Schritte geändert, die nicht wiederhergestellt werden konnten, daher wurde das Skript angehalten +@msg a recovery copy could not be written, so the script was not run eine Wiederherstellungskopie konnte nicht geschrieben werden, daher wurde das Skript nicht ausgeführt +@msg Running a script Skript wird ausgeführt @msg Copied the script report Skriptbericht kopiert @msg Corners edits the corners of a path „Ecken“ bearbeitet die Ecken eines Pfads @msg Couldn't copy to the system clipboard: {e} In die Systemzwischenablage konnte nicht kopiert werden: {e} @@ -5613,6 +5642,11 @@ axis Y Axis Y-Achse Button Schaltfläche Panel Bedienfeld UI Frames UI-Rahmen + Map Markers Kartenmarkierungen + Pin Stecknadel + Flag Flagge + Crosshair Fadenkreuz + Checkpoint Kontrollpunkt Open Symbol Library Symbol-Bibliothek öffnen Save Symbol Library Symbol-Bibliothek speichern Save Symbol Library… Symbol-Bibliothek speichern… diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index 7e1fb15850..b6a1ac9bde 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -2232,6 +2232,28 @@ axis Both Και τα δύο @msg Combine Slices: the slices have no bounds Συνδυασμός τομών: οι τομές δεν έχουν όρια @msg Convert to Artboards: selection has no area Μετατροπή σε πίνακες σχεδίασης: η επιλογή δεν έχει επιφάνεια @msg Convert to Shape: no rectangles or ellipses selected Μετατροπή σε σχήμα: δεν έχουν επιλεγεί ορθογώνια ή ελλείψεις + Run Εκτέλεση + Run Script Εκτέλεση σεναρίου + Stop Script Διακοπή σεναρίου + Show External Script Warning Εμφάνιση προειδοποίησης για εξωτερικά σενάρια + A Script Is Running Εκτελείται ένα σενάριο + 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 Να μην εμφανιστεί ξανά αυτή η προειδοποίηση + Stop the script and undo what it did? Then quit again. Διακοπή του σεναρίου και αναίρεση όσων έκανε; Έπειτα κάντε ξανά έξοδο. + This script has added a great many objects. Continue, or stop it and undo what it did? Αυτό το σενάριο πρόσθεσε πάρα πολλά αντικείμενα. Συνέχεια, ή διακοπή και αναίρεση όσων έκανε; +@msg Choose a .js or .jsx script Επιλέξτε ένα σενάριο .js ή .jsx +@msg Ran {name} Εκτελέστηκε: {name} +@msg The script was stopped and its changes were undone Το σενάριο διακόπηκε και οι αλλαγές του αναιρέθηκαν +@msg a script is running: stop it or wait for it to finish εκτελείται ένα σενάριο: διακόψτε το ή περιμένετε να τελειώσει +@msg this is a compiled script, which cannot be run; use its source text αυτό είναι μεταγλωττισμένο σενάριο που δεν μπορεί να εκτελεστεί· χρησιμοποιήστε το πηγαίο κείμενό του +@msg the script is not UTF-8 text το σενάριο δεν είναι κείμενο UTF-8 +@msg the script is too large to run το σενάριο είναι πολύ μεγάλο για εκτέλεση +@msg a drag or an undo group is open; finish it before running a script είναι ανοιχτή μια μεταφορά ή ομάδα αναίρεσης· ολοκληρώστε την πριν εκτελέσετε σενάριο +@msg the script left a document that cannot be kept το σενάριο άφησε ένα έγγραφο που δεν μπορεί να διατηρηθεί +@msg the script's run is no longer available η εκτέλεση του σεναρίου δεν είναι πλέον διαθέσιμη +@msg a failed command changed undo steps that could not be put back, so the script was stopped μια εντολή που απέτυχε άλλαξε βήματα αναίρεσης που δεν ήταν δυνατό να επαναφερθούν, οπότε το σενάριο σταμάτησε +@msg a recovery copy could not be written, so the script was not run δεν ήταν δυνατή η εγγραφή αντιγράφου ανάκτησης, οπότε το σενάριο δεν εκτελέστηκε +@msg Running a script Εκτελείται σενάριο @msg Copied the script report Η αναφορά του σεναρίου αντιγράφηκε @msg Corners edits the corners of a path Η εντολή Γωνίες επεξεργάζεται τις γωνίες μιας διαδρομής @msg Couldn't copy to the system clipboard: {e} Δεν ήταν δυνατή η αντιγραφή στο πρόχειρο συστήματος: {e} @@ -3579,6 +3601,13 @@ digits Malayalam Μαλαγιάλαμ Set Zoom Ορισμός ζουμ Setup… Ρύθμιση… Shadows and Glows Σκιές και λάμψεις + Game HUD HUD παιχνιδιού + Health Fill Υγεία + Mana Glow Μάνα + Damage Flash Ζημιά + Quest Outline Αποστολή + Coin Shine Νόμισμα + Boss Alert Αρχηγός Shape Builder Regions Περιοχές δημιουργίας σχημάτων Shape Effects Εφέ σχημάτων Shape Mode Λειτουργία σχήματος @@ -5981,6 +6010,11 @@ axis Y Axis Άξονας Y Button Κουμπί Panel Πίνακας UI Frames Πλαίσια UI + Map Markers Δείκτες χάρτη + Pin Καρφίτσα + Flag Σημαία + Crosshair Σταυρόνημα + Checkpoint Σημείο ελέγχου Open Symbol Library Άνοιγμα βιβλιοθήκης συμβόλων Save Symbol Library Αποθήκευση βιβλιοθήκης συμβόλων Save Symbol Library… Αποθήκευση βιβλιοθήκης συμβόλων… diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index ebd4165638..18562ab4a5 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -3139,6 +3139,13 @@ digits Malayalam Malayálam Settings… Ajustes… Setup… Configuración… Shadows and Glows Sombras y resplandores + Game HUD HUD de juego + Health Fill Salud + Mana Glow Maná + Damage Flash Daño + Quest Outline Misión + Coin Shine Moneda + Boss Alert Jefe Shape Forma Shape Builder Generador de formas Shape Builder Regions Regiones del generador de formas @@ -4067,6 +4074,28 @@ axis Both Ambos @msg Combine Slices: the slices have no bounds Combinar sectores: los sectores no tienen límites @msg Convert to Artboards: selection has no area Convertir en mesas de trabajo: la selección no tiene área @msg Convert to Shape: no rectangles or ellipses selected Convertir en forma: no hay rectángulos ni elipses seleccionados + Run Ejecutar + Run Script Ejecutar script + Stop Script Detener script + Show External Script Warning Mostrar advertencia de scripts externos + A Script Is Running Se está ejecutando un script + 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 + Stop the script and undo what it did? Then quit again. ¿Detener el script y deshacer lo que hizo? Después, vuelva a salir. + This script has added a great many objects. Continue, or stop it and undo what it did? Este script ha añadido muchísimos objetos. ¿Continuar, o detenerlo y deshacer lo que hizo? +@msg Choose a .js or .jsx script Elija un script .js o .jsx +@msg Ran {name} Se ejecutó {name} +@msg The script was stopped and its changes were undone El script se detuvo y sus cambios se deshicieron +@msg a script is running: stop it or wait for it to finish se está ejecutando un script: deténgalo o espere a que termine +@msg this is a compiled script, which cannot be run; use its source text este es un script compilado, que no se puede ejecutar; use su texto fuente +@msg the script is not UTF-8 text el script no es texto UTF-8 +@msg the script is too large to run el script es demasiado grande para ejecutarlo +@msg a drag or an undo group is open; finish it before running a script hay un arrastre o un grupo de deshacer abierto; termínelo antes de ejecutar un script +@msg the script left a document that cannot be kept el script dejó un documento que no se puede conservar +@msg the script's run is no longer available la ejecución del script ya no está disponible +@msg a failed command changed undo steps that could not be put back, so the script was stopped un comando fallido cambió pasos de deshacer que no se pudieron restaurar, así que el script se detuvo +@msg a recovery copy could not be written, so the script was not run no se pudo escribir una copia de recuperación, así que el script no se ejecutó +@msg Running a script Ejecutando un script @msg Copied the script report Se copió el informe del script @msg Corners edits the corners of a path Esquinas edita las esquinas de un trazado @msg Couldn't copy to the system clipboard: {e} No se pudo copiar al portapapeles del sistema: {e} @@ -5972,6 +6001,11 @@ axis Y Axis Eje Y Button Botón Panel Panel UI Frames Marcos de IU + Map Markers Marcadores de mapa + Pin Chincheta + Flag Bandera + Crosshair Punto de mira + Checkpoint Punto de control Open Symbol Library Abrir biblioteca de símbolos Save Symbol Library Guardar biblioteca de símbolos Save Symbol Library… Guardar biblioteca de símbolos… diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index 2923bee24d..3d24dca973 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -766,6 +766,13 @@ Other Library… Muu kirjasto… Graphic Style Libraries Grafiikkatyylikirjastot Shadows and Glows Varjot ja hehkut + Game HUD Peli-HUD + Health Fill Terveys + Mana Glow Mana + Damage Flash Vahinko + Quest Outline Tehtävä + Coin Shine Kolikko + Boss Alert Bossi Outlines and Rules Ääriviivat ja viivat Hand-Drawn Käsin piirretyt Gradient Finishes Liukuväriviimeistelyt @@ -4291,6 +4298,28 @@ imageTrace Outline Ääriviiva @msg Combine Slices: the slices have no bounds Yhdistä viipaleet: viipaleilla ei ole rajoja @msg Convert to Artboards: selection has no area Muunna piirtoalustoiksi: valinnalla ei ole pinta-alaa @msg Convert to Shape: no rectangles or ellipses selected Muunna muodoksi: suorakulmioita tai ellipsejä ei ole valittu + Run Suorita + Run Script Suorita komentosarja + Stop Script Pysäytä komentosarja + Show External Script Warning Näytä ulkoisten komentosarjojen varoitus + A Script Is Running Komentosarja on käynnissä + 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 + Stop the script and undo what it did? Then quit again. Pysäytetäänkö komentosarja ja kumotaan sen muutokset? Lopeta sitten uudelleen. + This script has added a great many objects. Continue, or stop it and undo what it did? Tämä komentosarja on lisännyt hyvin paljon objekteja. Jatketaanko, vai pysäytetäänkö se ja kumotaan sen muutokset? +@msg Choose a .js or .jsx script Valitse .js- tai .jsx-komentosarja +@msg Ran {name} Suoritettu: {name} +@msg The script was stopped and its changes were undone Komentosarja pysäytettiin ja sen muutokset kumottiin +@msg a script is running: stop it or wait for it to finish komentosarja on käynnissä: pysäytä se tai odota sen valmistumista +@msg this is a compiled script, which cannot be run; use its source text tämä on käännetty komentosarja, jota ei voi suorittaa; käytä sen lähdetekstiä +@msg the script is not UTF-8 text komentosarja ei ole UTF-8-tekstiä +@msg the script is too large to run komentosarja on liian suuri suoritettavaksi +@msg a drag or an undo group is open; finish it before running a script vetäminen tai kumousryhmä on kesken; viimeistele se ennen komentosarjan suorittamista +@msg the script left a document that cannot be kept komentosarja jätti asiakirjan, jota ei voi säilyttää +@msg the script's run is no longer available komentosarjan suoritus ei ole enää käytettävissä +@msg a failed command changed undo steps that could not be put back, so the script was stopped epäonnistunut komento muutti kumoamisvaiheita, joita ei voitu palauttaa, joten komentosarja pysäytettiin +@msg a recovery copy could not be written, so the script was not run palautuskopiota ei voitu kirjoittaa, joten komentosarjaa ei suoritettu +@msg Running a script Suoritetaan komentosarjaa @msg Copied the script report Komentosarjan raportti kopioitiin @msg Corners edits the corners of a path Kulmat-toiminto muokkaa polun kulmia @msg Couldn't copy to the system clipboard: {e} Järjestelmän leikepöydälle ei voitu kopioida: {e} @@ -6060,6 +6089,11 @@ axis Y Axis Y-akseli Button Painike Panel Paneeli UI Frames UI-kehykset + Map Markers Karttamerkit + Pin Nasta + Flag Lippu + Crosshair Tähtäin + Checkpoint Tarkastuskohta Open Symbol Library Avaa symbolikirjasto Save Symbol Library Tallenna symbolikirjasto Save Symbol Library… Tallenna symbolikirjasto… diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 43e44f3410..490be127b7 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -3131,6 +3131,13 @@ digits Malayalam Malayalam Settings… Réglages… Setup… Configuration… Shadows and Glows Ombres et lueurs + Game HUD HUD de jeu + Health Fill Santé + Mana Glow Mana + Damage Flash Dégâts + Quest Outline Quête + Coin Shine Pièce + Boss Alert Boss Shape Forme Shape Builder Concepteur de forme Shape Builder Regions Zones du Concepteur de forme @@ -4056,6 +4063,28 @@ axis Both Les deux @msg Combine Slices: the slices have no bounds Combiner les tranches : les tranches n’ont pas de limites @msg Convert to Artboards: selection has no area Convertir en plans de travail : la sélection n’a pas de surface @msg Convert to Shape: no rectangles or ellipses selected Convertir en forme : aucun rectangle ni aucune ellipse sélectionné + Run Exécuter + Run Script Exécuter le script + Stop Script Arrêter le script + Show External Script Warning Afficher l’avertissement des scripts externes + A Script Is Running Un script est en cours d’exécution + 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 + Stop the script and undo what it did? Then quit again. Arrêter le script et annuler ce qu’il a fait ? Quittez ensuite à nouveau. + This script has added a great many objects. Continue, or stop it and undo what it did? Ce script a ajouté un très grand nombre d’objets. Continuer, ou l’arrêter et annuler ce qu’il a fait ? +@msg Choose a .js or .jsx script Choisissez un script .js ou .jsx +@msg Ran {name} {name} exécuté +@msg The script was stopped and its changes were undone Le script a été arrêté et ses modifications ont été annulées +@msg a script is running: stop it or wait for it to finish un script est en cours d’exécution : arrêtez-le ou attendez qu’il se termine +@msg this is a compiled script, which cannot be run; use its source text ce script est compilé et ne peut pas être exécuté ; utilisez son texte source +@msg the script is not UTF-8 text le script n’est pas du texte UTF-8 +@msg the script is too large to run le script est trop volumineux pour être exécuté +@msg a drag or an undo group is open; finish it before running a script un glissement ou un groupe d’annulation est ouvert ; terminez-le avant d’exécuter un script +@msg the script left a document that cannot be kept le script a laissé un document qui ne peut pas être conservé +@msg the script's run is no longer available l’exécution du script n’est plus disponible +@msg a failed command changed undo steps that could not be put back, so the script was stopped une commande en échec a modifié des étapes d’annulation qui n’ont pas pu être rétablies, le script a donc été arrêté +@msg a recovery copy could not be written, so the script was not run une copie de récupération n’a pas pu être écrite, le script n’a donc pas été exécuté +@msg Running a script Exécution d’un script @msg Copied the script report Rapport du script copié @msg Corners edits the corners of a path Angles modifie les angles d’un tracé @msg Couldn't copy to the system clipboard: {e} Impossible de copier dans le presse-papiers du système : {e} @@ -6025,6 +6054,11 @@ axis Y Axis Axe Y Button Bouton Panel Panneau UI Frames Cadres d’IU + Map Markers Marqueurs de carte + Pin Épingle + Flag Drapeau + Crosshair Réticule + Checkpoint Point de contrôle Open Symbol Library Ouvrir une bibliothèque de symboles Save Symbol Library Enregistrer la bibliothèque de symboles Save Symbol Library… Enregistrer la bibliothèque de symboles… diff --git a/crates/ui-egui/src/i18n/hi.tsv b/crates/ui-egui/src/i18n/hi.tsv index db5ac56829..793319bd64 100644 --- a/crates/ui-egui/src/i18n/hi.tsv +++ b/crates/ui-egui/src/i18n/hi.tsv @@ -514,6 +514,11 @@ antiAlias Sharp शार्प Button बटन Panel पैनल UI Frames UI फ़्रेम + Map Markers मानचित्र चिह्न + Pin पिन + Flag झंडा + Crosshair क्रॉसहेयर + Checkpoint चेकपॉइंट Batch बैच Batch Trace Folder फ़ोल्डर बैच ट्रेस करें Batch… बैच… @@ -4233,6 +4238,13 @@ antiAlias Sharp शार्प Shading शेडिंग Shadow Intensity शैडो तीव्रता Shadows and Glows छाया और चमक + Game HUD गेम HUD + Health Fill स्वास्थ्य + Mana Glow माना + Damage Flash क्षति + Quest Outline क्वेस्ट + Coin Shine सिक्का + Boss Alert बॉस Shaft: दस्ता: Shape शेप Shape Builder शेप बिल्डर @@ -6134,6 +6146,28 @@ antiAlias Sharp शार्प @msg control must be fillStroke, coloring, drawMode or screenMode control को fillStroke, coloring, drawMode या screenMode होना चाहिए @msg Convert to Artboards: selection has no area आर्टबोर्ड में कनवर्ट करें: सिलेक्शन में कोई क्षेत्र नहीं है @msg Convert to Shape: no rectangles or ellipses selected आकार में कनवर्ट करें: कोई आयत या अंडाकार सिलेक्शन नहीं + Run चलाएँ + Run Script स्क्रिप्ट चलाएँ + Stop Script स्क्रिप्ट रोकें + Show External Script Warning बाहरी स्क्रिप्ट की चेतावनी दिखाएँ + A Script Is Running एक स्क्रिप्ट चल रही है + 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 यह चेतावनी फिर न दिखाएँ + Stop the script and undo what it did? Then quit again. स्क्रिप्ट रोककर उसके बदलाव पूर्ववत करें? फिर दोबारा बाहर निकलें। + This script has added a great many objects. Continue, or stop it and undo what it did? इस स्क्रिप्ट ने बहुत सारे ऑब्जेक्ट जोड़े हैं। जारी रखें, या इसे रोककर इसके बदलाव पूर्ववत करें? +@msg Choose a .js or .jsx script .js या .jsx स्क्रिप्ट चुनें +@msg Ran {name} {name} चलाई गई +@msg The script was stopped and its changes were undone स्क्रिप्ट रोकी गई और उसके बदलाव पूर्ववत किए गए +@msg a script is running: stop it or wait for it to finish एक स्क्रिप्ट चल रही है: उसे रोकें या पूरा होने की प्रतीक्षा करें +@msg this is a compiled script, which cannot be run; use its source text यह कंपाइल की हुई स्क्रिप्ट है, जिसे चलाया नहीं जा सकता; इसका स्रोत पाठ इस्तेमाल करें +@msg the script is not UTF-8 text स्क्रिप्ट UTF-8 पाठ नहीं है +@msg the script is too large to run स्क्रिप्ट चलाने के लिए बहुत बड़ी है +@msg a drag or an undo group is open; finish it before running a script कोई ड्रैग या पूर्ववत समूह खुला है; स्क्रिप्ट चलाने से पहले उसे पूरा करें +@msg the script left a document that cannot be kept स्क्रिप्ट ने ऐसा दस्तावेज़ छोड़ा है जिसे रखा नहीं जा सकता +@msg the script's run is no longer available स्क्रिप्ट का रन अब उपलब्ध नहीं है +@msg a failed command changed undo steps that could not be put back, so the script was stopped एक विफल कमांड ने पूर्ववत चरण बदल दिए जिन्हें वापस नहीं रखा जा सका, इसलिए स्क्रिप्ट रोक दी गई +@msg a recovery copy could not be written, so the script was not run रिकवरी प्रति नहीं लिखी जा सकी, इसलिए स्क्रिप्ट नहीं चलाई गई +@msg Running a script स्क्रिप्ट चल रही है @msg Copied the script report Copied स्क्रिप्ट रिपोर्ट @msg copy needs path: the file to copy into the document's folder copy: प्रतिलिपि की जरूरत है पाथ: फ़ाइल को डॉक्यूमेंट के फ़ोल्डर में कॉपी करने के लिए @msg copy takes images only: relink placed documents where their files are copy: प्रतिलिपि केवल इमेज को लेती है: डॉक्यूमेंट्स को फिर से लिंक करें जहां उनकी फ़ाइलें हैं diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index 54d303f688..9079e814f6 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -3753,6 +3753,13 @@ mark-style Japanese Japán Shades of Gray Szürkeárnyalatok Shading Árnyékolás Shadows and Glows Árnyékok és ragyogások + Game HUD Játék HUD + Health Fill Életerő + Mana Glow Mana + Damage Flash Sebzés + Quest Outline Küldetés + Coin Shine Érme + Boss Alert Főellenség Shape Alakzat Shape Builder Alakzatépítő Shape Builder Regions Alakzatépítő területei @@ -4862,6 +4869,28 @@ imageTrace Outline Körvonal @msg compressed (RLE) bitmaps can't be read yet a tömörített (RLE) bitképek még nem olvashatók @msg Convert to Artboards: selection has no area Átalakítás rajztáblákká: a kijelölésnek nincs területe @msg Convert to Shape: no rectangles or ellipses selected Átalakítás alakzattá: nincs kijelölt téglalap vagy ellipszis + Run Futtatás + 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 + A Script Is Running Egy parancsfájl fut + 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 + Stop the script and undo what it did? Then quit again. Leállítja a parancsfájlt, és visszavonja a módosításait? Ezután lépjen ki újra. + This script has added a great many objects. Continue, or stop it and undo what it did? Ez a parancsfájl nagyon sok objektumot adott hozzá. Folytatja, vagy leállítja és visszavonja a módosításait? +@msg Choose a .js or .jsx script Válasszon .js vagy .jsx parancsfájlt +@msg Ran {name} Lefutott: {name} +@msg The script was stopped and its changes were undone A parancsfájl leállt, a módosításai visszavonva +@msg a script is running: stop it or wait for it to finish egy parancsfájl fut: állítsa le, vagy várja meg, hogy befejeződjön +@msg this is a compiled script, which cannot be run; use its source text ez lefordított parancsfájl, amely nem futtatható; használja a forrásszövegét +@msg the script is not UTF-8 text a parancsfájl nem UTF-8 szöveg +@msg the script is too large to run a parancsfájl túl nagy a futtatáshoz +@msg a drag or an undo group is open; finish it before running a script húzás vagy visszavonási csoport van folyamatban; fejezze be a parancsfájl futtatása előtt +@msg the script left a document that cannot be kept a parancsfájl olyan dokumentumot hagyott hátra, amely nem tartható meg +@msg the script's run is no longer available a parancsfájl futása már nem érhető el +@msg a failed command changed undo steps that could not be put back, so the script was stopped egy sikertelen parancs olyan visszavonási lépéseket módosított, amelyeket nem lehetett visszaállítani, ezért a parancsfájl leállt +@msg a recovery copy could not be written, so the script was not run a helyreállítási másolatot nem sikerült kiírni, ezért a parancsfájl nem futott le +@msg Running a script Parancsfájl futtatása @msg Copied the script report Szkriptjelentés másolva @msg Corners edits the corners of a path a Sarkok parancs egy útvonal sarkait szerkeszti @msg could not decode image: {0} a kép nem dekódolható: {0} @@ -6013,6 +6042,11 @@ axis Y Axis Y tengely Button Gomb Panel Panel UI Frames UI keretek + Map Markers Térképjelölők + Pin Gombostű + Flag Zászló + Crosshair Célkereszt + Checkpoint Ellenőrzőpont Open Symbol Library Szimbólumkönyvtár megnyitása Save Symbol Library Szimbólumkönyvtár mentése Save Symbol Library… Szimbólumkönyvtár mentése… diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index 5188002c0b..99d5d14e8f 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -712,6 +712,13 @@ Other Library… Pustaka lain… Graphic Style Libraries Pustaka gaya grafis Shadows and Glows Bayangan dan pendar + Game HUD HUD Game + Health Fill Nyawa + Mana Glow Mana + Damage Flash Damage + Quest Outline Quest + Coin Shine Koin + Boss Alert Boss Outlines and Rules Garis luar dan garis Hand-Drawn Gambar tangan Gradient Finishes Finishing gradien @@ -4073,6 +4080,15 @@ imageTrace Outline Kontur @msg Combine Slices: the slices have no bounds Gabungkan irisan: irisan tidak memiliki batas @msg Convert to Artboards: selection has no area Konversi ke artboard: seleksi tidak memiliki area @msg Convert to Shape: no rectangles or ellipses selected Konversi ke bentuk: tidak ada persegi panjang atau elips yang dipilih + Run Jalankan + Run Script Jalankan Skrip + Stop Script Hentikan Skrip + Show External Script Warning Tampilkan Peringatan Skrip Eksternal + A Script Is Running Skrip Sedang Berjalan + 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 + Stop the script and undo what it did? Then quit again. Hentikan skrip dan batalkan yang telah dilakukannya? Lalu keluar lagi. + This script has added a great many objects. Continue, or stop it and undo what it did? Skrip ini telah menambahkan sangat banyak objek. Lanjutkan, atau hentikan dan batalkan yang telah dilakukannya? @msg Copied the script report Berhasil menyalin laporan skrip @msg Corners edits the corners of a path Corners menyunting sudut jalur @msg Couldn't copy to the system clipboard: {e} Tidak dapat menyalin ke papan klip sistem: {e} @@ -5850,6 +5866,11 @@ axis Y Axis Sumbu Y Button Tombol Panel Panel UI Frames Bingkai UI + Map Markers Penanda Peta + Pin Pin + Flag Bendera + Crosshair Bidik silang + Checkpoint Pos pemeriksaan Open Symbol Library Buka pustaka simbol Save Symbol Library Simpan pustaka simbol Save Symbol Library… Simpan pustaka simbol… diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index 726026fe42..92e1e801c8 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -3175,6 +3175,13 @@ digits Malayalam Malayalam Settings… Impostazioni… Setup… Configurazione… Shadows and Glows Ombre e bagliori + Game HUD HUD di gioco + Health Fill Salute + Mana Glow Mana + Damage Flash Danno + Quest Outline Missione + Coin Shine Moneta + Boss Alert Boss Shape Forma Shape Builder Generatore forme Shape Builder Regions Aree del Generatore forme @@ -4109,6 +4116,28 @@ axis Both Entrambi @msg Combine Slices: the slices have no bounds Combina sezioni: le sezioni non hanno limiti @msg Convert to Artboards: selection has no area Converti in tavole da disegno: la selezione non ha area @msg Convert to Shape: no rectangles or ellipses selected Converti in forma: nessun rettangolo o ellisse selezionato + Run Esegui + Run Script Esegui script + Stop Script Interrompi script + Show External Script Warning Mostra avviso per gli script esterni + A Script Is Running È in esecuzione uno script + 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 + Stop the script and undo what it did? Then quit again. Interrompere lo script e annullare ciò che ha fatto? Poi esci di nuovo. + This script has added a great many objects. Continue, or stop it and undo what it did? Questo script ha aggiunto moltissimi oggetti. Continuare, oppure interromperlo e annullare ciò che ha fatto? +@msg Choose a .js or .jsx script Scegli uno script .js o .jsx +@msg Ran {name} {name} eseguito +@msg The script was stopped and its changes were undone Lo script è stato interrotto e le sue modifiche sono state annullate +@msg a script is running: stop it or wait for it to finish è in esecuzione uno script: interrompilo o attendi che finisca +@msg this is a compiled script, which cannot be run; use its source text questo è uno script compilato, che non può essere eseguito; usa il suo testo sorgente +@msg the script is not UTF-8 text lo script non è testo UTF-8 +@msg the script is too large to run lo script è troppo grande per essere eseguito +@msg a drag or an undo group is open; finish it before running a script è aperto un trascinamento o un gruppo di annullamento; completalo prima di eseguire uno script +@msg the script left a document that cannot be kept lo script ha lasciato un documento che non può essere conservato +@msg the script's run is no longer available l'esecuzione dello script non è più disponibile +@msg a failed command changed undo steps that could not be put back, so the script was stopped un comando non riuscito ha modificato passaggi di annullamento che non è stato possibile ripristinare, quindi lo script è stato interrotto +@msg a recovery copy could not be written, so the script was not run non è stato possibile scrivere una copia di recupero, quindi lo script non è stato eseguito +@msg Running a script Esecuzione di uno script @msg Copied the script report Rapporto dello script copiato @msg Corners edits the corners of a path Angoli modifica gli angoli di un tracciato @msg Couldn't copy to the system clipboard: {e} Impossibile copiare negli appunti di sistema: {e} @@ -5647,6 +5676,11 @@ axis Y Axis Asse Y Button Pulsante Panel Pannello UI Frames Cornici UI + Map Markers Marcatori mappa + Pin Spillo + Flag Bandiera + Crosshair Mirino + Checkpoint Punto di controllo Open Symbol Library Apri libreria simboli Save Symbol Library Salva libreria simboli Save Symbol Library… Salva libreria simboli… diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index 4f8c7408be..bd08e72408 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -799,6 +799,13 @@ digits Malayalam マラヤーラム数字 Other Library… その他のライブラリ… Graphic Style Libraries グラフィックスタイルライブラリ Shadows and Glows シャドウと光彩 + Game HUD ゲーム HUD + Health Fill 体力 + Mana Glow マナ + Damage Flash ダメージ + Quest Outline クエスト + Coin Shine コイン + Boss Alert ボス Outlines and Rules アウトラインと罫線 Hand-Drawn 手描き風 Gradient Finishes グラデーション仕上げ @@ -4819,6 +4826,28 @@ swatch Bright Violet ビビッドバイオレット @msg the library item is damaged ライブラリの項目が破損しています @msg {_1} font families available {_1} 個のフォントファミリーを使用できます @msg {_1} has no {_2} style {_1} には {_2} スタイルがありません + Run 実行 + Run Script スクリプトを実行 + Stop Script スクリプトを停止 + Show External Script Warning 外部スクリプトの警告を表示 + A Script Is Running スクリプトの実行中 + 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 今後この警告を表示しない + Stop the script and undo what it did? Then quit again. スクリプトを停止して変更を取り消しますか?その後、もう一度終了してください。 + This script has added a great many objects. Continue, or stop it and undo what it did? このスクリプトは非常に多くのオブジェクトを追加しました。続行しますか、それとも停止して変更を取り消しますか? +@msg Choose a .js or .jsx script .js または .jsx スクリプトを選択してください +@msg Ran {name} {name} を実行しました +@msg The script was stopped and its changes were undone スクリプトを停止し、変更を取り消しました +@msg a script is running: stop it or wait for it to finish スクリプトの実行中です: 停止するか、終了するまでお待ちください +@msg this is a compiled script, which cannot be run; use its source text これはコンパイル済みのスクリプトなので実行できません。ソーステキストを使用してください +@msg the script is not UTF-8 text スクリプトは UTF-8 テキストではありません +@msg the script is too large to run スクリプトが大きすぎて実行できません +@msg a drag or an undo group is open; finish it before running a script ドラッグまたは取り消しグループが開いています。スクリプトを実行する前に完了してください +@msg the script left a document that cannot be kept スクリプトが保持できないドキュメントを残しました +@msg the script's run is no longer available スクリプトの実行は利用できなくなりました +@msg a failed command changed undo steps that could not be put back, so the script was stopped 失敗したコマンドが元に戻せない取り消し手順を変更したため、スクリプトを停止しました +@msg a recovery copy could not be written, so the script was not run 復元用のコピーを書き込めなかったため、スクリプトは実行されませんでした +@msg Running a script スクリプトを実行中 @msg Copied the script report スクリプトのレポートをコピーしました @msg Exported {path} {path} を書き出しました @msg no CSS to copy: select objects with CSS of their own コピーする CSS がありません: 独自の CSS を持つオブジェクトを選択してください @@ -5712,6 +5741,11 @@ axis Y Axis Y 軸 Button ボタン Panel パネル UI Frames UIフレーム + Map Markers マップマーカー + Pin ピン + Flag 旗 + Crosshair クロスヘア + Checkpoint チェックポイント Open Symbol Library シンボルライブラリを開く Save Symbol Library シンボルライブラリを保存 Save Symbol Library… シンボルライブラリを保存… diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index c21c3002b8..e2fbb790e7 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -662,6 +662,13 @@ Other Library… სხვა ბიბლიოთეკა… Graphic Style Libraries გრაფიკული სტილების ბიბლიოთეკები Shadows and Glows ჩრდილები და ნათებები + Game HUD თამაშის HUD + Health Fill სიცოცხლე + Mana Glow მანა + Damage Flash ზიანი + Quest Outline ქვესტი + Coin Shine მონეტა + Boss Alert ბოსი Outlines and Rules კონტურები და ხაზები Hand-Drawn ხელით დახატული Gradient Finishes გრადიენტული ზედაპირები @@ -5133,6 +5140,28 @@ mark-style Japanese იაპონური Auto Grouping ავტომატური დაჯგუფება Ignore Color ფერის იგნორირება imageTrace Outline კონტური + Run გაშვება + Run Script სკრიპტის გაშვება + Stop Script სკრიპტის შეჩერება + Show External Script Warning გარე სკრიპტის გაფრთხილების ჩვენება + A Script Is Running სკრიპტი მუშაობს + 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 აღარ აჩვენო ეს გაფრთხილება + Stop the script and undo what it did? Then quit again. შეჩერდეს სკრიპტი და გაუქმდეს მისი ცვლილებები? შემდეგ ხელახლა გამოდით. + This script has added a great many objects. Continue, or stop it and undo what it did? ამ სკრიპტმა ძალიან ბევრი ობიექტი დაამატა. გაგრძელდეს, თუ შეჩერდეს და გაუქმდეს მისი ცვლილებები? +@msg Choose a .js or .jsx script აირჩიეთ .js ან .jsx სკრიპტი +@msg Ran {name} გაშვებულია: {name} +@msg The script was stopped and its changes were undone სკრიპტი შეჩერდა და მისი ცვლილებები გაუქმდა +@msg a script is running: stop it or wait for it to finish სკრიპტი მუშაობს: შეაჩერეთ ან დაელოდეთ დასრულებას +@msg this is a compiled script, which cannot be run; use its source text ეს კომპილირებული სკრიპტია და მისი გაშვება შეუძლებელია; გამოიყენეთ მისი საწყისი ტექსტი +@msg the script is not UTF-8 text სკრიპტი არ არის UTF-8 ტექსტი +@msg the script is too large to run სკრიპტი გასაშვებად ძალიან დიდია +@msg a drag or an undo group is open; finish it before running a script ღიაა გადათრევა ან გაუქმების ჯგუფი; დაასრულეთ სკრიპტის გაშვებამდე +@msg the script left a document that cannot be kept სკრიპტმა დატოვა დოკუმენტი, რომლის შენახვა შეუძლებელია +@msg the script's run is no longer available სკრიპტის გაშვება აღარ არის ხელმისაწვდომი +@msg a failed command changed undo steps that could not be put back, so the script was stopped წარუმატებელმა ბრძანებამ შეცვალა გაუქმების ნაბიჯები, რომელთა აღდგენა ვერ მოხერხდა, ამიტომ სკრიპტი შეჩერდა +@msg a recovery copy could not be written, so the script was not run აღდგენის ასლის ჩაწერა ვერ მოხერხდა, ამიტომ სკრიპტი არ გაეშვა +@msg Running a script სკრიპტი მუშაობს @msg Copied the script report კოპირებულია სკრიპტის ანგარიში @msg Offset Path: the offset leaves nothing of the selected paths (an inset larger than the shapes) ტრაექტორიის წანაცვლება: წანაცვლების შემდეგ მონიშნული ტრაექტორიებიდან არაფერი რჩება (შიგნით წანაცვლება ფიგურებზე დიდია) @msg {path}: not a file {path}: ფაილი არ არის @@ -5953,6 +5982,11 @@ axis Y Axis Y ღერძი Button ღილაკი Panel პანელი UI Frames UI ჩარჩოები + Map Markers რუკის ნიშნულები + Pin ქინძისთავი + Flag დროშა + Crosshair სამიზნე + Checkpoint საკონტროლო წერტილი Open Symbol Library სიმბოლოების ბიბლიოთეკის გახსნა Save Symbol Library სიმბოლოების ბიბლიოთეკის შენახვა Save Symbol Library… სიმბოლოების ბიბლიოთეკის შენახვა… diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index c262be5b77..11d1532b6f 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -792,6 +792,13 @@ digits Malayalam 말라얄람어 Other Library… 다른 라이브러리… Graphic Style Libraries 그래픽 스타일 라이브러리 Shadows and Glows 그림자와 광선 + Game HUD 게임 HUD + Health Fill 체력 + Mana Glow 마나 + Damage Flash 피해 + Quest Outline 퀘스트 + Coin Shine 코인 + Boss Alert 보스 Outlines and Rules 윤곽선과 괘선 Hand-Drawn 손그림 Gradient Finishes 그레이디언트 마감 @@ -4746,6 +4753,28 @@ theme Appearance 외관 @msg the library item is damaged 라이브러리 항목이 손상되었습니다 @msg {_1} font families available 사용 가능한 글꼴 패밀리 {_1}개 @msg {_1} has no {_2} style {_1}에는 {_2} 스타일이 없습니다 + Run 실행 + Run Script 스크립트 실행 + Stop Script 스크립트 중지 + Show External Script Warning 외부 스크립트 경고 표시 + A Script Is Running 스크립트 실행 중 + 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 이 경고를 다시 표시하지 않음 + Stop the script and undo what it did? Then quit again. 스크립트를 중지하고 변경 내용을 취소할까요? 그런 다음 다시 종료하세요. + This script has added a great many objects. Continue, or stop it and undo what it did? 이 스크립트가 매우 많은 개체를 추가했습니다. 계속할까요, 아니면 중지하고 변경 내용을 취소할까요? +@msg Choose a .js or .jsx script .js 또는 .jsx 스크립트를 선택하세요 +@msg Ran {name} {name} 실행됨 +@msg The script was stopped and its changes were undone 스크립트를 중지하고 변경 내용을 취소했습니다 +@msg a script is running: stop it or wait for it to finish 스크립트 실행 중: 중지하거나 끝날 때까지 기다리세요 +@msg this is a compiled script, which cannot be run; use its source text 컴파일된 스크립트이므로 실행할 수 없습니다. 소스 텍스트를 사용하세요 +@msg the script is not UTF-8 text 스크립트가 UTF-8 텍스트가 아닙니다 +@msg the script is too large to run 스크립트가 너무 커서 실행할 수 없습니다 +@msg a drag or an undo group is open; finish it before running a script 드래그 또는 실행 취소 그룹이 열려 있습니다. 스크립트를 실행하기 전에 완료하세요 +@msg the script left a document that cannot be kept 스크립트가 유지할 수 없는 문서를 남겼습니다 +@msg the script's run is no longer available 스크립트 실행을 더 이상 사용할 수 없습니다 +@msg a failed command changed undo steps that could not be put back, so the script was stopped 실패한 명령이 되돌릴 수 없는 실행 취소 단계를 변경하여 스크립트를 중지했습니다 +@msg a recovery copy could not be written, so the script was not run 복구 사본을 쓸 수 없어 스크립트를 실행하지 않았습니다 +@msg Running a script 스크립트 실행 중 @msg Copied the script report 스크립트 보고서를 복사했습니다 @msg Exported {path} {path}을(를) 내보냈습니다 @msg no CSS to copy: select objects with CSS of their own 복사할 CSS가 없습니다: 자체 CSS가 있는 개체를 선택하세요 @@ -5608,6 +5637,11 @@ axis Y Axis Y축 Button 버튼 Panel 패널 UI Frames UI 프레임 + Map Markers 지도 마커 + Pin 핀 + Flag 깃발 + Crosshair 십자선 + Checkpoint 체크포인트 Open Symbol Library 심볼 라이브러리 열기 Save Symbol Library 심볼 라이브러리 저장 Save Symbol Library… 심볼 라이브러리 저장… diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index 36ab0e6642..b07008b394 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -726,6 +726,13 @@ Other Library… Andere bibliotheek… Graphic Style Libraries Bibliotheken met grafische stijlen Shadows and Glows Schaduwen en gloed + Game HUD Game-HUD + Health Fill Leven + Mana Glow Mana + Damage Flash Schade + Quest Outline Quest + Coin Shine Munt + Boss Alert Baas Outlines and Rules Omtrekken en lijnen Hand-Drawn Handgetekend Gradient Finishes Verloopafwerkingen @@ -4087,6 +4094,15 @@ imageTrace Outline Contour @msg Combine Slices: the slices have no bounds Slices combineren: de slices hebben geen grenzen @msg Convert to Artboards: selection has no area Converteren naar tekengebieden: de selectie heeft geen oppervlakte @msg Convert to Shape: no rectangles or ellipses selected Converteren naar vorm: geen rechthoeken of ellipsen geselecteerd + Run Uitvoeren + Run Script Script uitvoeren + Stop Script Script stoppen + Show External Script Warning Waarschuwing voor externe scripts tonen + A Script Is Running Er wordt een script uitgevoerd + 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 + Stop the script and undo what it did? Then quit again. Het script stoppen en de wijzigingen ervan ongedaan maken? Sluit daarna opnieuw af. + This script has added a great many objects. Continue, or stop it and undo what it did? Dit script heeft heel veel objecten toegevoegd. Doorgaan, of het stoppen en de wijzigingen ervan ongedaan maken? @msg Copied the script report Scriptrapport gekopieerd @msg Corners edits the corners of a path Hoeken bewerkt de hoeken van een pad @msg Couldn't copy to the system clipboard: {e} Kon niet naar het systeemklembord kopiëren: {e} @@ -5901,6 +5917,11 @@ axis Y Axis Y-as Button Knop Panel Paneel UI Frames UI-kaders + Map Markers Kaartmarkeringen + Pin Speld + Flag Vlag + Crosshair Vizier + Checkpoint Controlepunt Open Symbol Library Symboolbibliotheek openen Save Symbol Library Symboolbibliotheek opslaan Save Symbol Library… Symboolbibliotheek opslaan… diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index 47099ed184..d04dd6f476 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -722,6 +722,13 @@ Other Library… Inna biblioteka… Graphic Style Libraries Biblioteki stylów graficznych Shadows and Glows Cienie i blaski + Game HUD HUD gry + Health Fill Zdrowie + Mana Glow Mana + Damage Flash Obrażenia + Quest Outline Zadanie + Coin Shine Moneta + Boss Alert Boss Outlines and Rules Kontury i linie Hand-Drawn Rysowane odręcznie Gradient Finishes Wykończenia gradientowe @@ -4200,6 +4207,28 @@ imageTrace Outline Kontur @msg Combine Slices: the slices have no bounds Połącz plasterki: plasterki nie mają granic @msg Convert to Artboards: selection has no area Konwertuj na obszary kompozycji: zaznaczenie nie ma powierzchni @msg Convert to Shape: no rectangles or ellipses selected Konwertuj na kształt: nie zaznaczono prostokątów ani elips + Run Uruchom + Run Script Uruchom skrypt + Stop Script Zatrzymaj skrypt + Show External Script Warning Pokazuj ostrzeżenie o skryptach zewnętrznych + A Script Is Running Skrypt jest uruchomiony + 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 + Stop the script and undo what it did? Then quit again. Zatrzymać skrypt i cofnąć jego zmiany? Następnie zakończ program ponownie. + This script has added a great many objects. Continue, or stop it and undo what it did? Ten skrypt dodał bardzo wiele obiektów. Kontynuować, czy zatrzymać go i cofnąć jego zmiany? +@msg Choose a .js or .jsx script Wybierz skrypt .js lub .jsx +@msg Ran {name} Wykonano: {name} +@msg The script was stopped and its changes were undone Skrypt został zatrzymany, a jego zmiany cofnięte +@msg a script is running: stop it or wait for it to finish skrypt jest uruchomiony: zatrzymaj go lub poczekaj na jego zakończenie +@msg this is a compiled script, which cannot be run; use its source text to jest skrypt skompilowany, którego nie można uruchomić; użyj jego tekstu źródłowego +@msg the script is not UTF-8 text skrypt nie jest tekstem UTF-8 +@msg the script is too large to run skrypt jest zbyt duży, aby go uruchomić +@msg a drag or an undo group is open; finish it before running a script otwarte jest przeciąganie lub grupa cofania; zakończ je przed uruchomieniem skryptu +@msg the script left a document that cannot be kept skrypt pozostawił dokument, którego nie można zachować +@msg the script's run is no longer available uruchomienie skryptu nie jest już dostępne +@msg a failed command changed undo steps that could not be put back, so the script was stopped nieudane polecenie zmieniło kroki cofania, których nie udało się przywrócić, więc skrypt został zatrzymany +@msg a recovery copy could not be written, so the script was not run nie udało się zapisać kopii odzyskiwania, więc skrypt nie został uruchomiony +@msg Running a script Uruchamianie skryptu @msg Copied the script report Skopiowano raport skryptu @msg Corners edits the corners of a path Narożniki edytuje narożniki ścieżki @msg Couldn't copy to the system clipboard: {e} Nie udało się skopiować do schowka systemowego: {e} @@ -5884,6 +5913,11 @@ axis Y Axis Oś Y Button Przycisk Panel Panel UI Frames Ramki UI + Map Markers Znaczniki mapy + Pin Pinezka + Flag Flaga + Crosshair Celownik + Checkpoint Punkt kontrolny Open Symbol Library Otwórz bibliotekę symboli Save Symbol Library Zapisz bibliotekę symboli Save Symbol Library… Zapisz bibliotekę symboli… diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index 218ea24cd1..04161e336b 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -2631,6 +2631,13 @@ digits Malayalam Malaiala Set the selected color to the current color Definir a cor selecionada para a cor atual Setup… Configuração… Shadows and Glows Sombras e Brilhos + Game HUD HUD de jogo + Health Fill Vida + Mana Glow Mana + Damage Flash Dano + Quest Outline Missão + Coin Shine Moeda + Boss Alert Chefe Shape Forma Shape Builder Construtor de Formas Shape Builder Regions Regiões do Construtor de Formas @@ -5024,6 +5031,28 @@ axis Both Ambos [Normal Paragraph Style] [Estilo de Parágrafo Normal] Joins Junções Axis Eixo + Run Executar + Run Script Executar script + Stop Script Parar script + Show External Script Warning Mostrar aviso de scripts externos + A Script Is Running Um script está em execução + 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 + Stop the script and undo what it did? Then quit again. Parar o script e desfazer o que ele fez? Depois, saia novamente. + This script has added a great many objects. Continue, or stop it and undo what it did? Este script adicionou muitíssimos objetos. Continuar, ou pará-lo e desfazer o que ele fez? +@msg Choose a .js or .jsx script Escolha um script .js ou .jsx +@msg Ran {name} {name} executado +@msg The script was stopped and its changes were undone O script foi parado e suas alterações foram desfeitas +@msg a script is running: stop it or wait for it to finish um script está em execução: pare-o ou aguarde até que termine +@msg this is a compiled script, which cannot be run; use its source text este é um script compilado, que não pode ser executado; use seu texto-fonte +@msg the script is not UTF-8 text o script não é texto UTF-8 +@msg the script is too large to run o script é grande demais para ser executado +@msg a drag or an undo group is open; finish it before running a script há um arraste ou um grupo de desfazer aberto; conclua-o antes de executar um script +@msg the script left a document that cannot be kept o script deixou um documento que não pode ser mantido +@msg the script's run is no longer available a execução do script não está mais disponível +@msg a failed command changed undo steps that could not be put back, so the script was stopped um comando que falhou alterou etapas de desfazer que não puderam ser restauradas, então o script foi interrompido +@msg a recovery copy could not be written, so the script was not run não foi possível gravar uma cópia de recuperação, portanto o script não foi executado +@msg Running a script Executando um script @msg Copied the script report Relatório do script copiado @msg This shortcut file is in a form VectorCraft can't read. Este arquivo de atalhos está em um formato que o VectorCraft não consegue ler. @msg axis must be "vertical", "horizontal" or an angle in degrees, not `{v}` axis deve ser "vertical", "horizontal" ou um ângulo em graus, não `{v}` @@ -5945,6 +5974,11 @@ axis Y Axis Eixo Y Button Botão Panel Painel UI Frames Molduras de IU + Map Markers Marcadores de mapa + Pin Alfinete + Flag Bandeira + Crosshair Mira + Checkpoint Ponto de verificação Open Symbol Library Abrir Biblioteca de Símbolos Save Symbol Library Salvar Biblioteca de Símbolos Save Symbol Library… Salvar Biblioteca de Símbolos… diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index e76f24ae6f..e345d56184 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -3170,6 +3170,13 @@ digits Malayalam Малаялам Settings… Параметры… Setup… Настройка… Shadows and Glows Тени и свечения + Game HUD Игровой HUD + Health Fill Здоровье + Mana Glow Мана + Damage Flash Урон + Quest Outline Квест + Coin Shine Монета + Boss Alert Босс Shape Фигура Shape Builder Создание фигур Shape Builder Regions Области создания фигур @@ -4103,6 +4110,28 @@ axis Both Оба @msg Combine Slices: the slices have no bounds Объединение фрагментов: у фрагментов нет границ @msg Convert to Artboards: selection has no area Преобразование в монтажные области: у выделения нет области @msg Convert to Shape: no rectangles or ellipses selected Преобразование в фигуру: не выделены прямоугольники или эллипсы + Run Выполнить + Run Script Выполнить скрипт + Stop Script Остановить скрипт + Show External Script Warning Показывать предупреждение о внешних скриптах + A Script Is Running Выполняется скрипт + 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 Больше не показывать это предупреждение + Stop the script and undo what it did? Then quit again. Остановить скрипт и отменить его изменения? Затем выйдите ещё раз. + This script has added a great many objects. Continue, or stop it and undo what it did? Этот скрипт добавил очень много объектов. Продолжить или остановить его и отменить его изменения? +@msg Choose a .js or .jsx script Выберите скрипт .js или .jsx +@msg Ran {name} Выполнено: {name} +@msg The script was stopped and its changes were undone Скрипт остановлен, его изменения отменены +@msg a script is running: stop it or wait for it to finish выполняется скрипт: остановите его или дождитесь завершения +@msg this is a compiled script, which cannot be run; use its source text это скомпилированный скрипт, его нельзя выполнить; используйте его исходный текст +@msg the script is not UTF-8 text скрипт не является текстом UTF-8 +@msg the script is too large to run скрипт слишком велик для выполнения +@msg a drag or an undo group is open; finish it before running a script открыто перетаскивание или группа отмены; завершите их перед запуском скрипта +@msg the script left a document that cannot be kept скрипт оставил документ, который нельзя сохранить +@msg the script's run is no longer available выполнение скрипта больше недоступно +@msg a failed command changed undo steps that could not be put back, so the script was stopped неудавшаяся команда изменила шаги отмены, которые не удалось восстановить, поэтому скрипт остановлен +@msg a recovery copy could not be written, so the script was not run не удалось записать копию для восстановления, поэтому скрипт не выполнен +@msg Running a script Выполняется скрипт @msg Copied the script report Отчёт о сценарии скопирован @msg Corners edits the corners of a path «Углы» редактирует углы контура @msg Couldn't copy to the system clipboard: {e} Не удалось скопировать в системный буфер обмена: {e} @@ -5641,6 +5670,11 @@ axis Y Axis Ось Y Button Кнопка Panel Панель UI Frames UI-рамки + Map Markers Маркеры карты + Pin Булавка + Flag Флаг + Crosshair Прицел + Checkpoint Контрольная точка Open Symbol Library Открыть библиотеку символов Save Symbol Library Сохранить библиотеку символов Save Symbol Library… Сохранить библиотеку символов… diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index 3fa6df127f..f55e252b4b 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -3063,6 +3063,13 @@ digits Malayalam Malayalam Settings… Inställningar… Setup… Konfigurera… Shadows and Glows Skuggor och glöd + Game HUD Spel-HUD + Health Fill Hälsa + Mana Glow Mana + Damage Flash Skada + Quest Outline Uppdrag + Coin Shine Mynt + Boss Alert Boss Shape Form Shape Builder Formbyggare Shape Builder Regions Formbyggarområden @@ -3977,6 +3984,28 @@ axis Both Båda @msg Combine Slices: the slices have no bounds Kombinera skivor: skivorna har inga gränser @msg Convert to Artboards: selection has no area Konvertera till ritytor: markeringen har ingen area @msg Convert to Shape: no rectangles or ellipses selected Konvertera till form: inga rektanglar eller ellipser är markerade + Run Kör + Run Script Kör skript + Stop Script Stoppa skript + Show External Script Warning Visa varning för externa skript + A Script Is Running Ett skript körs + 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 + Stop the script and undo what it did? Then quit again. Stoppa skriptet och ångra det det gjort? Avsluta sedan igen. + This script has added a great many objects. Continue, or stop it and undo what it did? Det här skriptet har lagt till väldigt många objekt. Fortsätta, eller stoppa det och ångra det det gjort? +@msg Choose a .js or .jsx script Välj ett .js- eller .jsx-skript +@msg Ran {name} Körde {name} +@msg The script was stopped and its changes were undone Skriptet stoppades och dess ändringar ångrades +@msg a script is running: stop it or wait for it to finish ett skript körs: stoppa det eller vänta tills det är klart +@msg this is a compiled script, which cannot be run; use its source text det här är ett kompilerat skript som inte kan köras; använd dess källtext +@msg the script is not UTF-8 text skriptet är inte UTF-8-text +@msg the script is too large to run skriptet är för stort för att köras +@msg a drag or an undo group is open; finish it before running a script en dragning eller ångragrupp är öppen; avsluta den innan du kör ett skript +@msg the script left a document that cannot be kept skriptet lämnade ett dokument som inte kan behållas +@msg the script's run is no longer available skriptets körning är inte längre tillgänglig +@msg a failed command changed undo steps that could not be put back, so the script was stopped ett misslyckat kommando ändrade ångrasteg som inte kunde återställas, så skriptet stoppades +@msg a recovery copy could not be written, so the script was not run en återställningskopia kunde inte skrivas, så skriptet kördes inte +@msg Running a script Kör ett skript @msg Copied the script report Kopierade skriptrapporten @msg Corners edits the corners of a path Hörn redigerar hörnen på en bana @msg Couldn't copy to the system clipboard: {e} Kunde inte kopiera till systemets urklipp: {e} @@ -6053,6 +6082,11 @@ axis Y Axis Y-axel Button Knapp Panel Panel UI Frames UI-ramar + Map Markers Kartmarkörer + Pin Nål + Flag Flagga + Crosshair Hårkors + Checkpoint Kontrollpunkt Open Symbol Library Öppna symbolbibliotek Save Symbol Library Spara symbolbibliotek Save Symbol Library… Spara symbolbibliotek… diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index 2201aec721..a8a147c379 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -2967,6 +2967,13 @@ digits Malayalam Malayalam Settings… Ayarlar… Setup… Kurulum… Shadows and Glows Gölgeler ve Parıltılar + Game HUD Oyun HUD + Health Fill Can + Mana Glow Mana + Damage Flash Hasar + Quest Outline Görev + Coin Shine Jeton + Boss Alert Boss Shape Şekil Shape Builder Şekil Oluşturucu Shape Builder Regions Şekil Oluşturucu Bölgeleri @@ -3859,6 +3866,28 @@ axis Both Her İkisi @msg Combine Slices: the slices have no bounds Dilimleri Birleştir: dilimlerin sınırları yoktur @msg Convert to Artboards: selection has no area Çalışma Yüzeylerine Dönüştür: seçimin alanı yok @msg Convert to Shape: no rectangles or ellipses selected Şekle Dönüştür: seçili dikdörtgen veya elips yok + Run Çalıştır + Run Script Betiği Çalıştır + Stop Script Betiği Durdur + Show External Script Warning Harici Betik Uyarısını Göster + A Script Is Running Bir Betik Çalışıyor + 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 + Stop the script and undo what it did? Then quit again. Betik durdurulsun ve yaptıkları geri alınsın mı? Ardından yeniden çıkın. + This script has added a great many objects. Continue, or stop it and undo what it did? Bu betik çok sayıda nesne ekledi. Devam edilsin mi, yoksa durdurulup yaptıkları geri mi alınsın? +@msg Choose a .js or .jsx script Bir .js veya .jsx betiği seçin +@msg Ran {name} {name} çalıştırıldı +@msg The script was stopped and its changes were undone Betik durduruldu ve değişiklikleri geri alındı +@msg a script is running: stop it or wait for it to finish bir betik çalışıyor: durdurun veya bitmesini bekleyin +@msg this is a compiled script, which cannot be run; use its source text bu derlenmiş bir betik, çalıştırılamaz; kaynak metnini kullanın +@msg the script is not UTF-8 text betik UTF-8 metni değil +@msg the script is too large to run betik çalıştırılamayacak kadar büyük +@msg a drag or an undo group is open; finish it before running a script bir sürükleme veya geri alma grubu açık; betiği çalıştırmadan önce tamamlayın +@msg the script left a document that cannot be kept betik, saklanamayan bir belge bıraktı +@msg the script's run is no longer available betiğin çalıştırması artık kullanılamıyor +@msg a failed command changed undo steps that could not be put back, so the script was stopped başarısız bir komut geri yüklenemeyen geri alma adımlarını değiştirdi, bu yüzden betik durduruldu +@msg a recovery copy could not be written, so the script was not run kurtarma kopyası yazılamadı, bu nedenle betik çalıştırılmadı +@msg Running a script Betik çalıştırılıyor @msg Copied the script report Komut dosyası raporu kopyalandı @msg Corners edits the corners of a path Köşeler bir yolun köşelerini düzenler @msg Couldn't copy to the system clipboard: {e} Sistem panosuna kopyalanamadı: {e} @@ -5986,6 +6015,11 @@ axis Y Axis Y ekseni Button Düğme Panel Panel UI Frames UI çerçeveleri + Map Markers Harita İşaretleri + Pin İğne + Flag Bayrak + Crosshair Nişangah + Checkpoint Kontrol noktası Open Symbol Library Sembol Kitaplığını Aç Save Symbol Library Sembol Kitaplığını Kaydet Save Symbol Library… Sembol Kitaplığını Kaydet… diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index 25ee4d80ac..84ad648844 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -3167,6 +3167,13 @@ digits Malayalam Малаялам Settings… Параметри… Setup… Налаштування… Shadows and Glows Тіні та свічення + Game HUD Ігровий HUD + Health Fill Здоров'я + Mana Glow Мана + Damage Flash Шкода + Quest Outline Квест + Coin Shine Монета + Boss Alert Бос Shape Фігура Shape Builder Створення фігур Shape Builder Regions Області створення фігур @@ -4093,6 +4100,28 @@ axis Both Обидві @msg Combine Slices: the slices have no bounds Об’єднання фрагментів: фрагменти не мають кордонів @msg Convert to Artboards: selection has no area Перетворення на монтажні області: виділення не має області @msg Convert to Shape: no rectangles or ellipses selected Перетворення на фігуру: не виділено прямокутники або еліпси + Run Виконати + Run Script Виконати скрипт + Stop Script Зупинити скрипт + Show External Script Warning Показувати попередження про зовнішні скрипти + A Script Is Running Виконується скрипт + 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 Більше не показувати це попередження + Stop the script and undo what it did? Then quit again. Зупинити скрипт і скасувати його зміни? Потім вийдіть ще раз. + This script has added a great many objects. Continue, or stop it and undo what it did? Цей скрипт додав дуже багато об’єктів. Продовжити чи зупинити його та скасувати його зміни? +@msg Choose a .js or .jsx script Виберіть скрипт .js або .jsx +@msg Ran {name} Виконано: {name} +@msg The script was stopped and its changes were undone Скрипт зупинено, його зміни скасовано +@msg a script is running: stop it or wait for it to finish виконується скрипт: зупиніть його або дочекайтеся завершення +@msg this is a compiled script, which cannot be run; use its source text це скомпільований скрипт, його не можна виконати; використайте його вихідний текст +@msg the script is not UTF-8 text скрипт не є текстом UTF-8 +@msg the script is too large to run скрипт завеликий для виконання +@msg a drag or an undo group is open; finish it before running a script відкрито перетягування або групу скасування; завершіть їх перед запуском скрипта +@msg the script left a document that cannot be kept скрипт залишив документ, який не можна зберегти +@msg the script's run is no longer available виконання скрипта більше не доступне +@msg a failed command changed undo steps that could not be put back, so the script was stopped невдала команда змінила кроки скасування, які не вдалося відновити, тому скрипт зупинено +@msg a recovery copy could not be written, so the script was not run не вдалося записати копію для відновлення, тому скрипт не виконано +@msg Running a script Виконується скрипт @msg Copied the script report Звіт про сценарій скопійовано @msg Corners edits the corners of a path «Кути» редагує кути контуру @msg Couldn't copy to the system clipboard: {e} Не вдалося скопіювати до системного буфера обміну: {e} @@ -5627,6 +5656,11 @@ axis Y Axis Вісь Y Button Кнопка Panel Панель UI Frames UI-рамки + Map Markers Маркери карти + Pin Шпилька + Flag Прапор + Crosshair Приціл + Checkpoint Контрольна точка Open Symbol Library Відкрити бібліотеку символів Save Symbol Library Зберегти бібліотеку символів Save Symbol Library… Зберегти бібліотеку символів… diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index 7a6fdc5bd4..b0ec349fd0 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -3499,6 +3499,13 @@ mark-style Japanese Kiểu Nhật Setup… Thiết lập… Shading Tô bóng Shadows and Glows Bóng và ánh sáng + Game HUD HUD trò chơi + Health Fill Máu + Mana Glow Mana + Damage Flash Sát thương + Quest Outline Nhiệm vụ + Coin Shine Xu + Boss Alert Trùm Shape Hình dạng Shape Builder Tạo hình dạng Shape Builder Regions Vùng Tạo hình dạng @@ -4511,6 +4518,28 @@ theme Appearance Giao diện @msg compressed (RLE) bitmaps can't be read yet bitmap nén (RLE) chưa thể đọc được @msg Convert to Artboards: selection has no area Chuyển thành bảng vẽ: vùng chọn không có diện tích @msg Convert to Shape: no rectangles or ellipses selected Chuyển thành hình dạng: chưa chọn hình chữ nhật hay hình elip + Run Chạy + 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 + A Script Is Running Một tập lệnh đang chạy + 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 + Stop the script and undo what it did? Then quit again. Dừng tập lệnh và hoàn tác những gì nó đã làm? Sau đó hãy thoát lại. + This script has added a great many objects. Continue, or stop it and undo what it did? Tập lệnh này đã thêm rất nhiều đối tượng. Tiếp tục, hay dừng lại và hoàn tác những gì nó đã làm? +@msg Choose a .js or .jsx script Chọn một tập lệnh .js hoặc .jsx +@msg Ran {name} Đã chạy {name} +@msg The script was stopped and its changes were undone Tập lệnh đã dừng và các thay đổi của nó đã được hoàn tác +@msg a script is running: stop it or wait for it to finish một tập lệnh đang chạy: hãy dừng nó hoặc chờ nó kết thúc +@msg this is a compiled script, which cannot be run; use its source text đây là tập lệnh đã biên dịch, không thể chạy; hãy dùng văn bản nguồn của nó +@msg the script is not UTF-8 text tập lệnh không phải là văn bản UTF-8 +@msg the script is too large to run tập lệnh quá lớn để chạy +@msg a drag or an undo group is open; finish it before running a script đang có thao tác kéo hoặc nhóm hoàn tác; hãy hoàn thành trước khi chạy tập lệnh +@msg the script left a document that cannot be kept tập lệnh để lại một tài liệu không thể giữ +@msg the script's run is no longer available lần chạy tập lệnh không còn khả dụng +@msg a failed command changed undo steps that could not be put back, so the script was stopped một lệnh thất bại đã thay đổi các bước hoàn tác không thể khôi phục, nên tập lệnh đã bị dừng +@msg a recovery copy could not be written, so the script was not run không thể ghi bản sao khôi phục nên tập lệnh không được chạy +@msg Running a script Đang chạy tập lệnh @msg Copied the script report Đã sao chép báo cáo script @msg Corners edits the corners of a path Corners chỉnh sửa các góc của đường dẫn @msg could not decode image: {0} không thể giải mã ảnh: {0} @@ -5628,6 +5657,11 @@ axis Y Axis Trục Y Button Nút Panel Bảng UI Frames Khung UI + Map Markers Đánh dấu bản đồ + Pin Ghim + Flag Cờ + Crosshair Tâm ngắm + Checkpoint Điểm kiểm tra Open Symbol Library Mở thư viện ký hiệu Save Symbol Library Lưu thư viện ký hiệu Save Symbol Library… Lưu thư viện ký hiệu… diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index 1f11aa4d6c..ff1413b2fd 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -3005,6 +3005,13 @@ digits Malayalam 马拉雅拉姆数字 Settings… 设置… Setup… 设置… Shadows and Glows 阴影与光晕 + Game HUD 游戏 HUD + Health Fill 生命 + Mana Glow 法力 + Damage Flash 伤害 + Quest Outline 任务 + Coin Shine 金币 + Boss Alert 首领 Shape 形状 Shape Builder 形状生成器 Shape Builder Regions 形状生成器区域 @@ -4526,6 +4533,28 @@ imageTrace Outline 轮廓 @msg the library item is damaged 库项目已损坏 @msg {_1} font families available 有 {_1} 个可用的字体系列 @msg {_1} has no {_2} style {_1} 没有 {_2} 样式 + Run 运行 + Run Script 运行脚本 + Stop Script 停止脚本 + Show External Script Warning 显示外部脚本警告 + A Script Is Running 脚本正在运行 + 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 不再显示此警告 + Stop the script and undo what it did? Then quit again. 要停止脚本并撤销其更改吗?然后请再次退出。 + This script has added a great many objects. Continue, or stop it and undo what it did? 此脚本已添加大量对象。要继续,还是停止并撤销其更改? +@msg Choose a .js or .jsx script 请选择 .js 或 .jsx 脚本 +@msg Ran {name} 已运行 {name} +@msg The script was stopped and its changes were undone 脚本已停止,其更改已撤销 +@msg a script is running: stop it or wait for it to finish 脚本正在运行:请停止它或等待其完成 +@msg this is a compiled script, which cannot be run; use its source text 这是已编译的脚本,无法运行;请使用其源文本 +@msg the script is not UTF-8 text 脚本不是 UTF-8 文本 +@msg the script is too large to run 脚本过大,无法运行 +@msg a drag or an undo group is open; finish it before running a script 拖动或撤销组尚未结束;请在运行脚本前完成 +@msg the script left a document that cannot be kept 脚本留下了无法保留的文档 +@msg the script's run is no longer available 脚本运行已不可用 +@msg a failed command changed undo steps that could not be put back, so the script was stopped 失败的命令更改了无法恢复的撤销步骤,因此脚本已停止 +@msg a recovery copy could not be written, so the script was not run 无法写入恢复副本,因此未运行脚本 +@msg Running a script 正在运行脚本 @msg Copied the script report 已复制脚本报告 @msg Exported {path} 已导出 {path} @msg no CSS to copy: select objects with CSS of their own 没有可复制的 CSS:请选择带有自身 CSS 的对象 @@ -5868,6 +5897,11 @@ axis Y Axis Y 轴 Button 按钮 Panel 面板 UI Frames UI 框架 + Map Markers 地图标记 + Pin 图钉 + Flag 旗帜 + Crosshair 准星 + Checkpoint 检查点 Open Symbol Library 打开符号库 Save Symbol Library 保存符号库 Save Symbol Library… 保存符号库… diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index 9997599d8c..1d6d850820 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -2370,6 +2370,28 @@ file-filter Templates 範本 @msg the library item is damaged 資料庫項目已損毀 @msg {_1} font families available 有 {_1} 個可用的字體家族 @msg {_1} has no {_2} style {_1} 沒有 {_2} 樣式 + Run 執行 + Run Script 執行指令碼 + Stop Script 停止指令碼 + Show External Script Warning 顯示外部指令碼警告 + A Script Is Running 指令碼正在執行 + 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 不再顯示此警告 + Stop the script and undo what it did? Then quit again. 要停止指令碼並還原其變更嗎?然後請再次結束。 + This script has added a great many objects. Continue, or stop it and undo what it did? 此指令碼已新增大量物件。要繼續,還是停止並還原其變更? +@msg Choose a .js or .jsx script 請選擇 .js 或 .jsx 指令碼 +@msg Ran {name} 已執行 {name} +@msg The script was stopped and its changes were undone 指令碼已停止,其變更已還原 +@msg a script is running: stop it or wait for it to finish 指令碼正在執行:請停止它或等待其完成 +@msg this is a compiled script, which cannot be run; use its source text 這是已編譯的指令碼,無法執行;請使用其原始文字 +@msg the script is not UTF-8 text 指令碼不是 UTF-8 文字 +@msg the script is too large to run 指令碼過大,無法執行 +@msg a drag or an undo group is open; finish it before running a script 拖曳或還原群組尚未結束;請在執行指令碼前完成 +@msg the script left a document that cannot be kept 指令碼留下了無法保留的文件 +@msg the script's run is no longer available 指令碼執行已無法使用 +@msg a failed command changed undo steps that could not be put back, so the script was stopped 失敗的命令變更了無法還原的復原步驟,因此指令碼已停止 +@msg a recovery copy could not be written, so the script was not run 無法寫入復原副本,因此未執行指令碼 +@msg Running a script 正在執行指令碼 @msg Copied the script report 已複製指令碼報告 @msg Exported {path} 已匯出 {path} @msg no CSS to copy: select objects with CSS of their own 沒有可複製的 CSS:請選取有自己 CSS 的物件 @@ -4068,6 +4090,13 @@ digits Malayalam 馬來亞拉姆數字 Settings… 設定… Setup… 設定… Shadows and Glows 陰影與光暈 + Game HUD 遊戲 HUD + Health Fill 生命 + Mana Glow 魔力 + Damage Flash 傷害 + Quest Outline 任務 + Coin Shine 金幣 + Boss Alert 首領 Shape 形狀 Shape Builder 形狀建立 Shape Builder Regions 形狀建立區域 @@ -5665,6 +5694,11 @@ axis Y Axis Y 軸 Button 按鈕 Panel 面板 UI Frames UI 框架 + Map Markers 地圖標記 + Pin 圖釘 + Flag 旗幟 + Crosshair 準星 + Checkpoint 檢查點 Open Symbol Library 開啟符號資料庫 Save Symbol Library 儲存符號資料庫 Save Symbol Library… 儲存符號資料庫… diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 03acb7597e..932520b184 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -65,6 +65,7 @@ pub mod print; pub mod recovery; pub mod render_worker; pub mod screen_color; +pub mod script_runs; mod scrub; pub mod shortcut_editor; pub mod shortcuts; @@ -186,6 +187,8 @@ pub struct VectorcraftApp { frame_rate: frame_rate::FrameRate, /// Canvas rect of the last frame (screen points), for control-channel coordinate mapping. pub canvas_rect: Option, + /// An unfinished control-channel Rotate View gesture, kept only for this app instance. + pub(crate) control_rotate_press: Option, /// Hover position in document coordinates. pub hover_doc: Option, /// System clipboard: SVG to publish next frame, the last SVG we published (so pasting it back diff --git a/crates/ui-egui/src/menus/bar.rs b/crates/ui-egui/src/menus/bar.rs index c57a216370..cbc1536fc3 100644 --- a/crates/ui-egui/src/menus/bar.rs +++ b/crates/ui-egui/src/menus/bar.rs @@ -127,7 +127,7 @@ pub(super) fn render_items(app: &VectorcraftApp, ui: &mut egui::Ui, items: &[Ite ui.menu_button(label, |ui| { widgets::menu_scroll(ui, |ui| { ui.set_min_width(200.0); - render_items(app, ui, children, checks, clicked); + render_items(app, ui, children, checks || only_toggles(app, children), clicked); }); }); } @@ -136,6 +136,13 @@ pub(super) fn render_items(app: &VectorcraftApp, ui: &mut egui::Ui, items: &[Ite } } +/// Whether every item of a submenu can be on or off: a menu drawn without check marks (the canvas +/// context menu) still shows them there, since its label alone can't say whether it is on. +fn only_toggles(app: &VectorcraftApp, items: &[Item]) -> bool { + let mut rows = items.iter().filter_map(|it| entry(app, it)).filter(|e| !matches!(e, Entry::Sep)).peekable(); + rows.peek().is_some() && rows.all(|e| matches!(e, Entry::Item(r) if r.checked.is_some())) +} + /// One menu item: its label (with a check mark, or the room for one, under `checks`), its shortcut, /// and Type › Font's samples. fn render_row(app: &VectorcraftApp, ui: &mut egui::Ui, row: &Row, checks: bool, clicked: &mut Option<(String, Value)>) { diff --git a/crates/ui-egui/src/menus/context.rs b/crates/ui-egui/src/menus/context.rs index 387cd099cd..abf43a3584 100644 --- a/crates/ui-egui/src/menus/context.rs +++ b/crates/ui-egui/src/menus/context.rs @@ -92,6 +92,10 @@ pub fn context_items(app: &VectorcraftApp) -> Vec { // The paragraphs of the selected type, or those the Type tool's selection touches. if crate::panels::character::text_style(app).is_some() { v.push(sub("Bullets and Numbering", vec![c("Apply Bullets", "type.applyBullets"), c("Apply Numbers", "type.applyNumbers")])); + // A right-click on type turns Auto Spell Check on or off, as Edit › Spelling does, per + // the public [Check and correct spelling](https://helpx.adobe.com/illustrator/desktop/design-with-text/edit-format-text/check-and-correct-spelling.html) + // page. Its submenu holds only toggles, so it shows the check mark (`render_items`). + v.push(sub("Spelling", vec![c("Auto Spell Check", "edit.autoSpellCheck")])); } v.extend([c("Make Guides", "view.guides.make"), Sep, sub("Transform", transform_items())]); if intertwine.is_none() { @@ -265,7 +269,8 @@ fn prune(app: &VectorcraftApp, items: Vec) -> Vec { pub fn context_menu_body(app: &VectorcraftApp, ui: &mut egui::Ui, clicked: &mut Option<(String, Value)>) { widgets::menu_scroll(ui, |ui| { ui.set_min_width(200.0); - // Its toggles already say what they do (Show Rulers, Hide Guides): no check-mark gutter. + // Its toggles already say what they do (Show Rulers, Hide Guides): no check-mark gutter, + // except in a submenu of toggles alone (Spelling › Auto Spell Check). render_items(app, ui, &context_items(app), false, clicked); }); } diff --git a/crates/ui-egui/src/menus/run.rs b/crates/ui-egui/src/menus/run.rs index 9ec98faae7..92186e9f3d 100644 --- a/crates/ui-egui/src/menus/run.rs +++ b/crates/ui-egui/src/menus/run.rs @@ -969,6 +969,7 @@ fn run_ui_part13(app: &mut VectorcraftApp, id: &str, p: &Value) -> Option Ok(crate::trace_runs::cancel_all(app)), "imageTrace.hideRuns" => Ok(crate::trace_runs::hide_all(app)), "ui.checkScript" => crate::dialogs::script_check::command(app, p), + "ui.runScript" => crate::dialogs::script_run::command(app, p), "ui.perspectiveGridDialog" => crate::dialogs::perspective_grid::open(app), "ui.perspectivePresetsDialog" => { crate::dialogs::perspective_presets::open(app, s("selected").as_deref()); diff --git a/crates/ui-egui/src/menus/tree.rs b/crates/ui-egui/src/menus/tree.rs index c51f36e7de..ebea83e905 100644 --- a/crates/ui-egui/src/menus/tree.rs +++ b/crates/ui-egui/src/menus/tree.rs @@ -62,7 +62,7 @@ pub fn menu_tree_named(english_names: bool) -> Vec<(&'static str, Vec)> { c("Export Selection…", "file.exportSelection"), Sep, c("Package…", "ui.packageDialog"), - sub("Scripts", vec![c("Check Script…", "ui.checkScript"), todos("Other Script…", "Cmd+F12")]), + sub("Scripts", vec![c("Check Script…", "ui.checkScript"), c("Other Script…", "ui.runScript")]), Sep, c("Document Setup…", "file.documentSetup"), sub( diff --git a/crates/ui-egui/src/menus/ui_commands.rs b/crates/ui-egui/src/menus/ui_commands.rs index 3b314f8335..fb78fc2075 100644 --- a/crates/ui-egui/src/menus/ui_commands.rs +++ b/crates/ui-egui/src/menus/ui_commands.rs @@ -1520,6 +1520,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}", ), + ( + "ui.runScript", + "Other Script…", + "Cmd+F12", + "{path? | source?, name?} run a .js or .jsx file (script.run), after the warning unless Preferences › General › Show External Script Warning is off (dialog `scriptRun`: `name`, `script`, `dontShow`); without a file pick one (the web opens the browser's file picker)", + ), ( "ui.checkScript", "Check Script…", diff --git a/crates/ui-egui/src/panel_docking.rs b/crates/ui-egui/src/panel_docking.rs index a74f47b6a9..3447cd1e15 100644 --- a/crates/ui-egui/src/panel_docking.rs +++ b/crates/ui-egui/src/panel_docking.rs @@ -949,6 +949,7 @@ impl Transaction { } if let Some(saved) = &location.group { apply(&mut candidate, Action::ResizeGroup { panel: panel.clone(), height: saved.height })?; + apply(&mut candidate, Action::ResizeFlyoutWidth { panel: panel.clone(), width: saved.flyout_width })?; apply(&mut candidate, Action::SetMinimized { panel: panel.clone(), minimized: saved.minimized })?; } self.workspace.layout = candidate; @@ -1087,6 +1088,7 @@ fn known(action: &Action) -> bool { | Action::SetIconic { panel, .. } | Action::ResizeColumn { panel, .. } | Action::ResizeGroup { panel, .. } + | Action::ResizeFlyoutWidth { panel, .. } | Action::ResizeIconic { panel, .. } | Action::SetNative { panel, .. } | Action::SetMonitor { panel, .. } => registered(panel), @@ -1169,7 +1171,7 @@ pub(crate) fn show(app: &mut VectorcraftApp, ui: &mut egui::Ui) { if let Some(panel) = app.dock_rt.raise.take() { dock = dock.raise_panel(panel); } - let mut output = dock.show_content(ui, &layout, &style, &mut PanelContent { app: &mut *app }); + let mut output = dock.show_content(ui, &layout, &style, &mut PanelContent { app: &mut *app, layout: &layout }); app.dock_rt.space = craft_ui::docking::float_space(&ctx, area); if let Some(panel) = output.focused.take() { app.dock_rt.focused = Some(panel); @@ -1343,9 +1345,11 @@ pub(crate) fn floating_size(panel: &str) -> egui::Vec2 { /// The panels' content, labels and icons. struct PanelContent<'a> { app: &'a mut VectorcraftApp, + layout: &'a Layout, } impl craft_ui::docking::DockContent for PanelContent<'_> { + /// Draw a registered panel body, fitting untouched flyouts and pinning sized panels' footers. fn body(&mut self, ui: &mut egui::Ui, id: &String) { if id == CANVAS { crate::toolbar::show_beside_canvas(self.app, ui); @@ -1364,15 +1368,23 @@ impl craft_ui::docking::DockContent for PanelContent<'_> { } let width = ui.available_width(); let height = (ui.available_height() - 20.0).max(0.0); - if DockTab::from_id(id).is_some() { - crate::dock::panel_body(self.app, ui, id, width, height); - } else { - // Shrinking to the content's height lets craft-ui fit a float or flyout to it. - crate::widgets::panel_scroll(ui, egui::ScrollArea::vertical().id_salt(("shared-panel-body", id)).auto_shrink([false, true]), |ui| { - let width = ui.available_width(); - crate::dock::panel_body(self.app, ui, id, width, height) - }); - } + let fitted = in_iconic_column(self.layout, id) + && self.layout.location(id).ok().and_then(|location| location.group).is_none_or(|group| group.height.is_none()); + // Properties embeds other panels as sections, so their local button rows + // must remain beside those sections rather than pinning to the outer panel. + let bottom = (!fitted && id != "properties").then_some(back.bottom() - 10.0); + let info = egui::UiStackInfo::default().with_tag_value(crate::widgets::PANEL_FOOTER, bottom); + ui.scope_builder(egui::UiBuilder::new().ui_stack_info(info), |ui| { + if DockTab::from_id(id).is_some() { + crate::dock::panel_body(self.app, ui, id, width, height); + } else { + // Shrinking to the content's height lets craft-ui fit a float or flyout to it. + crate::widgets::panel_scroll(ui, egui::ScrollArea::vertical().id_salt(("shared-panel-body", id)).auto_shrink([false, true]), |ui| { + let width = ui.available_width(); + crate::dock::panel_body(self.app, ui, id, width, height) + }); + } + }); if field_had_keyboard { keep_field_ending_keys(ui); } diff --git a/crates/ui-egui/src/panel_docking/tests.rs b/crates/ui-egui/src/panel_docking/tests.rs index 1b8b1a168a..2d33420b9e 100644 --- a/crates/ui-egui/src/panel_docking/tests.rs +++ b/crates/ui-egui/src/panel_docking/tests.rs @@ -12,13 +12,16 @@ struct Harness { app: VectorcraftApp, ctx: egui::Context, time: f64, + cursor: egui::CursorIcon, + nodes: Vec<(egui::accesskit::NodeId, egui::accesskit::Node)>, } impl Harness { + /// Create a blank document and settle the initial docking layout over three frames. fn new() -> Self { let mut app = VectorcraftApp::new(Session::new(), Default::default()); app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); - let mut h = Self { app, ctx: egui::Context::default(), time: 0.0 }; + let mut h = Self { app, ctx: egui::Context::default(), time: 0.0, cursor: egui::CursorIcon::Default, nodes: Vec::new() }; for _ in 0..3 { h.frame(vec![]); } @@ -40,6 +43,7 @@ impl Harness { self.run(input); } + /// Draw one application frame and retain its cursor and accessibility output for assertions. fn run(&mut self, input: egui::RawInput) { let app = &mut self.app; let mut out = self.ctx.run_ui(input, |ui| { @@ -47,6 +51,8 @@ impl Harness { app.ui(ui); }); out.textures_delta.clear(); + self.cursor = out.platform_output.cursor_icon; + self.nodes = out.platform_output.accesskit_update.map_or_else(Vec::new, |update| update.nodes); } fn hit(&self, hit: &Hit) -> Option { @@ -138,6 +144,120 @@ fn an_icon_opens_its_flyout_and_open_panel_follows() { assert_eq!(craft_ui::docking::flyout::(&h.ctx, area_id()), None); } +/// #5713: real Glyphs and Artboards bodies must retain a flyout resize through +/// content fitting, closing/reopening and serialization of the workspace layout. +#[test] +fn glyphs_and_artboards_flyouts_keep_user_sizes() { + for panel in ["glyphs", "artboards"] { + let mut h = Harness::new(); + let icon = h.hit(&Hit::Icon(panel.into())).unwrap().center(); + h.click(icon); + // Glyphs reserves space from the available height, so its untouched auto-fit + // converges over several frames before the first user resize. + for _ in 0..30 { + h.frame(vec![]); + } + // Area memory can include a panel body's minimum allocation beyond its clip. + // The frame's actual edge widgets describe the visible, resizable rectangle. + let rect = |h: &Harness| { + let id = area_id().with("flyout"); + let left = h.ctx.read_response(id.with("resize-left")).unwrap().rect; + let bottom = h.ctx.read_response(id.with("resize-bottom")).unwrap().rect; + Rect::from_min_max(pos2(left.left(), left.top() - 12.0), pos2(bottom.right() + 12.0, bottom.bottom())) + }; + let before = rect(&h); + for (at, cursor) in [ + (before.left_center() + vec2(2.0, 0.0), egui::CursorIcon::ResizeHorizontal), + (before.center_bottom() - vec2(0.0, 2.0), egui::CursorIcon::ResizeVertical), + ] { + h.frame(vec![Event::PointerMoved(at)]); + h.frame(vec![]); + assert_eq!(h.cursor, cursor, "{panel} at {at:?}, frame {before:?}"); + } + let from = before.left_bottom() + vec2(2.0, -2.0); + h.drag(from, from + vec2(-100.0, 150.0)); + for _ in 0..3 { + h.frame(vec![]); + } + let grown = rect(&h); + assert!((grown.width() - before.width() - 100.0).abs() < 1.0, "{panel}: {before:?} -> {grown:?}"); + assert!((grown.height() - before.height() - 150.0).abs() < 1.0, "{panel}: {before:?} -> {grown:?}"); + assert_eq!(grown.right(), before.right(), "the icon-column edge stays anchored"); + h.click(icon); + assert_eq!(craft_ui::docking::flyout::(&h.ctx, area_id()), None); + h.click(icon); + for _ in 0..3 { + h.frame(vec![]); + } + assert_eq!(rect(&h).size(), grown.size()); + let saved = serde_json::to_string(&h.layout()).unwrap(); + let mut restored = Harness::new(); + restored.app.ui.docking = Some(serde_json::from_str(&saved).unwrap()); + for _ in 0..3 { + restored.frame(vec![]); + } + restored.click(restored.hit(&Hit::Icon(panel.into())).unwrap().center()); + for _ in 0..3 { + restored.frame(vec![]); + } + assert_eq!(rect(&restored).size(), grown.size(), "{panel} saved layout"); + } +} + +/// Footer controls stay at the resized panel's bottom, including empty or short lists. +/// The same shared footer is used by the other icon panels and library windows. +#[test] +fn expanded_panel_footers_stay_at_the_bottom_with_short_and_long_lists() { + for (panel, label, artboards) in [ + ("artboards", "New Artboard", 1), + ("artboards", "New Artboard", 30), + ("brushes", "New Brush", 1), + ("swatches", "New Swatch", 1), + ("symbols", "New Symbol", 1), + ("graphicStyles", "New Graphic Style (Alt-click to name it)", 1), + ("appearance", "Add New Stroke", 1), + ("charStyles", "Create New Character Style", 1), + ("paraStyles", "Create New Paragraph Style", 1), + ("colorGuide", "Save color group to Swatch panel", 1), + ("links", "Show Link Info", 1), + ("actions", "Create New Action", 1), + ("variables", "Capture Data Set", 1), + ("assetExport", "Export for Screens…", 1), + ("cssProperties", "Generate CSS: the whole document's CSS while nothing is selected", 1), + ("svgInteractivity", "Link JavaScript Files…", 1), + ("colorThemes", "Add to Swatches", 1), + ("glyphs", "Zoom In", 1), + ] { + let mut h = Harness::new(); + h.ctx.enable_accesskit(); + for _ in 1..artboards { + h.app.run("artboard.new", json!({})).unwrap(); + } + h.app.run("window.panel.dock", json!({"panel":panel,"icon":true})).unwrap(); + let mut layout = h.layout(); + layout.apply(Action::ResizeGroup { panel: panel.into(), height: Some(540.0) }).unwrap(); + layout.apply(Action::ResizeFlyoutWidth { panel: panel.into(), width: Some(420.0) }).unwrap(); + h.app.ui.docking = Some(layout); + h.app.ui.open_panel = Some(panel.into()); + for _ in 0..5 { + h.frame(vec![]); + } + let bottom = h.ctx.read_response(area_id().with("flyout").with("resize-bottom")).unwrap().rect.bottom(); + let control = h + .nodes + .iter() + .find(|(_, node)| node.label() == Some(label)) + .and_then(|(_, node)| node.bounds()) + .unwrap_or_else(|| panic!("missing {label} in {panel}")); + assert!((control.y1 as f32 - (bottom - 10.0)).abs() < 2.0, "{panel}/{artboards}: footer {control:?}, bottom {bottom}"); + if panel == "artboards" && artboards == 1 { + let at = pos2(((control.x0 + control.x1) * 0.5) as f32, ((control.y0 + control.y1) * 0.5) as f32); + h.click(at); + assert_eq!(h.app.session.active().unwrap().doc.artboards.len(), 2, "the pinned New button works"); + } + } +} + #[test] fn a_tab_dragged_out_floats_and_comes_back_where_it_was_after_its_window_closes() { let mut h = Harness::new(); diff --git a/crates/ui-egui/src/panels/actions.rs b/crates/ui-egui/src/panels/actions.rs index 93d781e5ae..2533ef0292 100644 --- a/crates/ui-egui/src/panels/actions.rs +++ b/crates/ui-egui/src/panels/actions.rs @@ -1377,6 +1377,7 @@ enum InclusionChange { Step(usize, usize, usize, bool), } +/// Draw action sets, steps and playback controls, keeping the list above a pinned footer. pub fn show(app: &mut VectorcraftApp, ui: &mut egui::Ui) { let t = Tokens::get(ui.ctx()); // The selected action as (set, action). Read as the type it is stored as: egui keeps a @@ -1398,7 +1399,8 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut egui::Ui) { let mut expanded: BTreeSet = pstate(ui.ctx(), "actions-expanded"); let mut inclusion_changes = Vec::new(); let mut play_req = None; - egui::ScrollArea::vertical().max_height(260.0).show(ui, |ui| { + let list_height = widgets::panel_list_height(ui, 260.0, 0.0).min(260.0); + egui::ScrollArea::vertical().max_height(list_height).min_scrolled_height(list_height.min(64.0)).show(ui, |ui| { for (si, set) in app.ui.action_sets.iter().enumerate() { let (r, resp) = ui.allocate_exact_size(egui::vec2(ui.available_width(), 20.0), egui::Sense::click()); if sets_selected.contains(&si) && selected.is_none() { @@ -1551,9 +1553,11 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut egui::Ui) { set_pstate(ui.ctx(), SELECTED_STEP, step_selected); app.ui.action_set = current; app.ui.action_sets_selected = sets_selected; - widgets::divider(ui); + if app.ui.action_sets.is_empty() { + dim_label(ui, tl!("No actions. Press ● to record.")); + } // Bottom bar: stop, record, play, new set, new action, delete. - ui.horizontal(|ui| { + widgets::bottom_bar(ui, |ui| { let recording = app.ui.recording.is_some(); if widgets::icon_button(ui, "square", tl!("Stop Playing/Recording"), false, 24.0).clicked() && let Err(e) = app.run(STOP_RECORDING, json!({})) @@ -1598,9 +1602,6 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut egui::Ui) { app.status(e); } let _ = icons::exists; - if app.ui.action_sets.is_empty() { - dim_label(ui, tl!("No actions. Press ● to record.")); - } } #[cfg(test)] @@ -1608,6 +1609,57 @@ mod tests { use super::*; use vectorcraft_engine::Session; + /// A short sized panel clips the list above its footer and can scroll to select its final row. + #[test] + fn a_short_actions_panel_keeps_its_last_row_reachable_above_the_footer() { + use egui::{Event, PointerButton, Rect, UiBuilder, UiStackInfo, pos2, vec2}; + for height in [60.0, 120.0] { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + let ctx = egui::Context::default(); + let mut time = 0.0; + let mut frame = |app: &mut VectorcraftApp, events| { + time += 0.1; + let input = egui::RawInput { + time: Some(time), + screen_rect: Some(Rect::from_min_size(pos2(0.0, 0.0), vec2(300.0, height))), + events, + ..Default::default() + }; + let mut output = ctx.run_ui(input, |ui| { + let info = UiStackInfo::default().with_tag_value(widgets::PANEL_FOOTER, Some(height)); + ui.scope_builder(UiBuilder::new().ui_stack_info(info), |ui| show(app, ui)); + }); + output.textures_delta.clear(); + output.shapes + }; + let last_row = |shapes: &[egui::epaint::ClippedShape]| { + shapes + .iter() + .find_map(|shape| match &shape.shape { + egui::Shape::Text(text) if text.galley.text() == "Reflect Horizontal" => Some((text.visual_bounding_rect(), shape.clip_rect)), + _ => None, + }) + .expect("the final action is drawn") + }; + for _ in 0..3 { + let shapes = frame(&mut app, vec![]); + assert!(last_row(&shapes).1.bottom() <= height - 31.0, "height={height}: the list overlaps its footer"); + } + for _ in 0..12 { + frame(&mut app, crate::toolbar::tests::wheel(pos2(100.0, 12.0), 1000.0)); + } + let shapes = frame(&mut app, vec![]); + let (row, clip) = last_row(&shapes); + assert!(clip.contains_rect(row), "height={height}: the final row {row:?} is outside {clip:?}"); + let at = row.center(); + let button = |pressed| Event::PointerButton { pos: at, button: PointerButton::Primary, pressed, modifiers: Default::default() }; + for events in [vec![Event::PointerMoved(at)], vec![button(true)], vec![button(false)]] { + frame(&mut app, events); + } + assert_eq!(pstate::>(&ctx, "actions-selected"), Some((0, 5))); + } + } + #[test] fn defaults_are_valid_commands() { for set in default_sets() { diff --git a/crates/ui-egui/src/panels/artboards.rs b/crates/ui-egui/src/panels/artboards.rs index d46e5c4ac3..04f2719e76 100644 --- a/crates/ui-egui/src/panels/artboards.rs +++ b/crates/ui-egui/src/panels/artboards.rs @@ -503,6 +503,7 @@ fn select_copies(app: &mut VectorcraftApp, all: &[usize], r: &Value) { } } +/// Draw the artboard list and its commands, filling the space above a sized panel's footer. pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { let t = Tokens::get(ui.ctx()); let abs: Vec = app.session.active().map(|d| d.doc.artboards.iter().map(|a| a.name.clone()).collect()).unwrap_or_default(); @@ -517,10 +518,17 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { let mut row_clicked = false; // A row dropped on another row: (from, to), the index it lands at. let mut dropped = None; + let fixed = widgets::panel_footer_bottom(ui).is_some(); + let list_height = widgets::panel_list_height(ui, 220.0, 2.0 + ui.spacing().item_spacing.y); let list_rect = widgets::list_box(ui, |ui| { - ui.set_min_height(110.0); + ui.set_min_height(if fixed { list_height.min(110.0) } else { 110.0 }); ui.spacing_mut().item_spacing.y = 0.0; - let scrolled = egui::ScrollArea::vertical().id_salt("ab-scroll").max_height(220.0).show(ui, |ui| { + let scroll = egui::ScrollArea::vertical() + .id_salt("ab-scroll") + .max_height(list_height) + .min_scrolled_height(list_height.min(64.0)) + .auto_shrink([false, !fixed]); + let scrolled = scroll.show(ui, |ui| { for (i, name) in abs.iter().enumerate() { let (r, resp) = ui.allocate_exact_size(vec2(ui.available_width(), 24.0), Sense::click_and_drag()); if resp.drag_started() { diff --git a/crates/ui-egui/src/panels/glyphs.rs b/crates/ui-egui/src/panels/glyphs.rs index 5c07441bee..9192aa5f0b 100644 --- a/crates/ui-egui/src/panels/glyphs.rs +++ b/crates/ui-egui/src/panels/glyphs.rs @@ -212,6 +212,7 @@ fn insert(app: &mut VectorcraftApp, ctx: &egui::Context, ch: char) { } } +/// Browse and insert glyphs from the chosen font, with font controls below the glyph grid. pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { let t = Tokens::get(ui.ctx()); let db = FontDb::global(); @@ -244,14 +245,14 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { let cols = ((w / cell).floor() as usize).max(1); let rows = chars.len().div_ceil(cols); let px = (cell * ui.ctx().pixels_per_point()).round().clamp(8.0, 256.0) as u32; - let list_h = (ui.available_height() - 64.0).max(cell * 3.0); + let list_h = widgets::panel_list_height(ui, (ui.available_height() - 64.0).max(cell * 3.0), 33.0); let hover_id = egui::Id::unique("gl-hover"); let selected = selected_char(app); // The selected character and the rows shown last frame: the grid scrolls to the selected glyph // only when the selection moves to another character, so it still scrolls freely meanwhile. let follow_id = egui::Id::unique("gl-follow"); let (followed, shown): (Option, std::ops::Range) = ui.ctx().data(|d| d.get_temp(follow_id)).unwrap_or_default(); - let mut area = egui::ScrollArea::vertical().max_height(list_h).auto_shrink([false, false]); + let mut area = egui::ScrollArea::vertical().max_height(list_h).min_scrolled_height(list_h.min(64.0)).auto_shrink([false, false]); if selected != followed && let Some(c) = selected && let Ok(i) = chars.binary_search_by_key(&c, |x| x.0) @@ -308,6 +309,7 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { /// The family and style menus of the font the panel browses, and Zoom Out and Zoom In. fn font_row(app: &mut VectorcraftApp, ui: &mut Ui, family: &str, style: &str, w: f32) { let db = FontDb::global(); + widgets::panel_footer_space(ui, 24.0); ui.horizontal(|ui| { ui.spacing_mut().item_spacing.x = 4.0; // Picks the font the panel browses only: nothing is previewed on the document. @@ -371,10 +373,14 @@ fn alternates(app: &mut VectorcraftApp, ui: &mut Ui, w: f32) { let cols = ((w / cell).floor() as usize).max(1); let rows = list.len().div_ceil(cols); let px = (cell * ui.ctx().pixels_per_point()).round().clamp(8.0, 256.0) as u32; - let list_h = (ui.available_height() - 64.0).max(cell * 3.0); + let list_h = widgets::panel_list_height(ui, (ui.available_height() - 64.0).max(cell * 3.0), 33.0); let mut pick = None; // A scroll position of its own for each character, so the grid starts at the top for another. - let area = egui::ScrollArea::vertical().id_salt(("gl-alternates", id.0, byte)).max_height(list_h).auto_shrink([false, false]); + let area = egui::ScrollArea::vertical() + .id_salt(("gl-alternates", id.0, byte)) + .max_height(list_h) + .min_scrolled_height(list_h.min(64.0)) + .auto_shrink([false, false]); area.show_rows(ui, cell, rows, |ui, range| { for r in range { ui.horizontal(|ui| { diff --git a/crates/ui-egui/src/panels/layers/thumbs.rs b/crates/ui-egui/src/panels/layers/thumbs.rs index 4fcdc03e49..2f15878133 100644 --- a/crates/ui-egui/src/panels/layers/thumbs.rs +++ b/crates/ui-egui/src/panels/layers/thumbs.rs @@ -928,6 +928,7 @@ mod tests { thumbs.receive(ctx, done); } + /// Prioritize the shown document’s thumbnails, requeue them when revisited, and retain cached rows. #[test] fn the_shown_documents_thumbnails_are_made_before_the_queued_ones_of_another() { let ctx = egui::Context::default(); @@ -957,10 +958,15 @@ mod tests { assert!(thumbs.texture(&ctx, &src_b, n, 24).is_some(), "the shown document's thumbnails are shown"); } // Shown again, document 1's rows are asked for again and come back. + // Hold the worker so texture() cannot collect a completed row before the count. + let release = hold(&thumbs); for n in &a_rows { assert!(thumbs.texture(&ctx, &src_a, n, 24).is_none()); } assert_eq!(thumbs.pending.keys().filter(|k| k.0 == 1).count(), 3); + release.send(()).expect("the held job is waiting"); + let held = thumbs.worker.as_ref().and_then(ThumbWorker::wait).expect("the held job finishes"); + assert_eq!(held.key.0, (0, NodeId(0))); for _ in &a_rows { receive_checked(&ctx, &mut thumbs, 1, &a, &a_rows); } diff --git a/crates/ui-egui/src/panels/tests_symbol_libraries.rs b/crates/ui-egui/src/panels/tests_symbol_libraries.rs index 6482bf3123..7dee49df2b 100644 --- a/crates/ui-egui/src/panels/tests_symbol_libraries.rs +++ b/crates/ui-egui/src/panels/tests_symbol_libraries.rs @@ -113,7 +113,7 @@ fn the_window_menu_and_the_symbols_panel_open_symbol_libraries() { let under = |e: &crate::menus::MenuEntry| e.path == ["Window", "Symbol Libraries"]; let opened: Vec<_> = entries.iter().filter(|e| under(e) && e.command.as_deref() == Some("window.symbolLibrary")).map(|e| e.params["library"].clone()).collect(); - assert_eq!(opened, [json!("basic-shapes"), json!("ui-frames")]); + assert_eq!(opened, [json!("basic-shapes"), json!("ui-frames"), json!("map-markers")]); let has = |cmd: &str| entries.iter().find(|e| under(e) && e.command.as_deref() == Some(cmd)).map(|e| e.enabled); assert_eq!(has("window.symbolLibrary.other"), Some(true)); assert_eq!(has("ui.saveSymbolLibrary"), Some(false), "no symbols to save yet"); diff --git a/crates/ui-egui/src/panels/variables.rs b/crates/ui-egui/src/panels/variables.rs index 87aa5cd13f..a8987855eb 100644 --- a/crates/ui-egui/src/panels/variables.rs +++ b/crates/ui-egui/src/panels/variables.rs @@ -97,6 +97,7 @@ pub(crate) fn delete_active_dataset(app: &mut VectorcraftApp) { app.run("dataset.delete", json!({})).ok(); } +/// Draw document variables, data sets and their two-row footer of capture and binding controls. pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { let Some(st) = app.session.active() else { widgets::dim_label(ui, tl!("No document")); @@ -209,46 +210,49 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { // The bottom bar: make the selection dynamic, define and delete what the lists show, and // lock the variables. - ui.separator(); - ui.horizontal(|ui| { - if widgets::icon_button_enabled(ui, "type", tl!("Make Text Dynamic"), false, single_type && !locked, 24.0).clicked() { - app.run("variable.makeTextDynamic", json!({})).ok(); - } - if widgets::icon_button_enabled(ui, "eye", tl!("Make Visibility Dynamic"), false, has_selection && !locked, 24.0).clicked() { - app.run("variable.makeVisibilityDynamic", json!({})).ok(); - } - if widgets::icon_button_enabled(ui, "image", tl!("Make Image Dynamic"), false, single_image && !locked, 24.0).clicked() { - app.run("variable.makeImageDynamic", json!({})).ok(); - } - if widgets::icon_button_enabled(ui, "chart-column", tl!("Make Graph Dynamic"), false, selection_graph && !locked, 24.0).clicked() { - app.run("variable.makeGraphDynamic", json!({})).ok(); - } - if widgets::icon_button_enabled(ui, "plus", tl!("New Variable…"), false, !locked, 24.0).clicked() { - crate::menus::invoke(app, "variable.define", json!({})); - } - if widgets::icon_button_enabled(ui, "link-2-off", tl!("Unbind Variable"), false, selection_bound, 24.0).clicked() { - app.run("variable.unbind", json!({"ids": selected})).ok(); - } - // The bin deletes the highlighted variable only, as the reference panel's does. - if widgets::icon_button_enabled(ui, "trash-2", tl!("Delete Variable"), false, highlighted.is_some() && !locked, 24.0).clicked() { - delete_highlighted(app); - } - // The lock button is drawn pressed while the variables are locked. - let tip = if locked { tl!("Unlock Variables") } else { tl!("Lock Variables") }; - if widgets::icon_button(ui, "lock", tip, locked, 24.0).clicked() { - app.run("variable.lock", json!({})).ok(); - } - }); - ui.horizontal(|ui| { - // Capture records what the art holds now as a new row (paste: take it in); Update - // writes the art back into the row that is active (save: write it out). - if widgets::icon_button(ui, "clipboard-paste", tl!("Capture Data Set"), false, 24.0).clicked() { - app.run("dataset.capture", json!({})).ok(); - } - let can_update = active.is_some(); - if widgets::icon_button_enabled(ui, "save", tl!("Update Data Set"), false, can_update, 24.0).clicked() { - app.run("dataset.update", json!({})).ok(); - } + let footer_height = 48.0 + 2.0 * ui.spacing().item_spacing.y + 1.0; + widgets::panel_footer(ui, footer_height, |ui| { + ui.add(egui::Separator::default().spacing(1.0)); + ui.horizontal(|ui| { + if widgets::icon_button_enabled(ui, "type", tl!("Make Text Dynamic"), false, single_type && !locked, 24.0).clicked() { + app.run("variable.makeTextDynamic", json!({})).ok(); + } + if widgets::icon_button_enabled(ui, "eye", tl!("Make Visibility Dynamic"), false, has_selection && !locked, 24.0).clicked() { + app.run("variable.makeVisibilityDynamic", json!({})).ok(); + } + if widgets::icon_button_enabled(ui, "image", tl!("Make Image Dynamic"), false, single_image && !locked, 24.0).clicked() { + app.run("variable.makeImageDynamic", json!({})).ok(); + } + if widgets::icon_button_enabled(ui, "chart-column", tl!("Make Graph Dynamic"), false, selection_graph && !locked, 24.0).clicked() { + app.run("variable.makeGraphDynamic", json!({})).ok(); + } + if widgets::icon_button_enabled(ui, "plus", tl!("New Variable…"), false, !locked, 24.0).clicked() { + crate::menus::invoke(app, "variable.define", json!({})); + } + if widgets::icon_button_enabled(ui, "link-2-off", tl!("Unbind Variable"), false, selection_bound, 24.0).clicked() { + app.run("variable.unbind", json!({"ids": selected})).ok(); + } + // The bin deletes the highlighted variable only, as the reference panel's does. + if widgets::icon_button_enabled(ui, "trash-2", tl!("Delete Variable"), false, highlighted.is_some() && !locked, 24.0).clicked() { + delete_highlighted(app); + } + // The lock button is drawn pressed while the variables are locked. + let tip = if locked { tl!("Unlock Variables") } else { tl!("Lock Variables") }; + if widgets::icon_button(ui, "lock", tip, locked, 24.0).clicked() { + app.run("variable.lock", json!({})).ok(); + } + }); + ui.horizontal(|ui| { + // Capture records what the art holds now as a new row (paste: take it in); Update + // writes the art back into the row that is active (save: write it out). + if widgets::icon_button(ui, "clipboard-paste", tl!("Capture Data Set"), false, 24.0).clicked() { + app.run("dataset.capture", json!({})).ok(); + } + let can_update = active.is_some(); + if widgets::icon_button_enabled(ui, "save", tl!("Update Data Set"), false, can_update, 24.0).clicked() { + app.run("dataset.update", json!({})).ok(); + } + }); }); } diff --git a/crates/ui-egui/src/picks.rs b/crates/ui-egui/src/picks.rs index 28a4d9d114..4122c19410 100644 --- a/crates/ui-egui/src/picks.rs +++ b/crates/ui-egui/src/picks.rs @@ -72,6 +72,7 @@ const DOCUMENT_FREE: &[&str] = &[ "file.newFromTemplate", "ui.installPlugin", "ui.checkScript", + "ui.runScript", "window.swatchLibrary.other", "window.graphicStyleLibrary.other", "ui.libraryPanel.locate", diff --git a/crates/ui-egui/src/script_runs.rs b/crates/ui-egui/src/script_runs.rs new file mode 100644 index 0000000000..042e24cd31 --- /dev/null +++ b/crates/ui-egui/src/script_runs.rs @@ -0,0 +1,48 @@ +//! A running script, advanced one slice per frame: `script.run` starts it and [`poll`] takes it to +//! its end, while the app goes on drawing the documents as they were before the run. The status bar +//! shows it with a Stop button; a run that has added a great deal waits for the person's answer. + +use serde_json::json; + +use crate::VectorcraftApp; +use crate::dialogs::script_run; +use crate::state::Dialog; + +/// Advances the running script by one slice, or asks what its growth needs asked. +pub fn poll(app: &mut VectorcraftApp) { + script_run::drain(app); + if !app.session.script_running() { + return; + } + if app.session.script_waiting() { + if app.ui.dialog.is_none() { + app.ui.dialog = Some(Dialog::new(script_run::GROWTH_KIND, json!({}))); + } + return; + } + 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 { return }; + if cursor_settings != (app.session.caps_lock, app.session.prefs.use_precise_cursors) { + app.canvas.hover_cursor = None; + } + if app.ui.dialog.as_ref().is_some_and(|d| d.kind == script_run::GROWTH_KIND) { + app.ui.dialog = None; + } + match result { + Ok(_) => app.status(format!("Ran {name}")), + Err(e) => failed(app, e.to_string()), + } + app.sync_views(); +} + +/// 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) { + let stopped = app.session.script_report().is_some_and(|r| r["kind"] == "stopped" && r["written"].as_array().is_none_or(Vec::is_empty)); + if stopped { + app.status("The script was stopped and its changes were undone"); + } else { + app.status(error); + } +} diff --git a/crates/ui-egui/src/services.rs b/crates/ui-egui/src/services.rs index 47374c7e69..901c0a3409 100644 --- a/crates/ui-egui/src/services.rs +++ b/crates/ui-egui/src/services.rs @@ -107,6 +107,11 @@ pub struct Services { /// Files that arrived asynchronously to be placed (web: picked for Place, or dropped on the /// canvas). pub place_inbox: Option, + /// Web: start an async pick of a script to run (it arrives via `script_inbox`; a canceled pick + /// delivers nothing). + pub script_async: Option>, + /// Scripts the web's picker delivered for File › Scripts › Other Script…. + pub script_inbox: Option, /// The system clipboard with all its formats (desktop): Copy offers text, SVG, PDF and PNG, /// Paste takes SVG, PDF, text and bitmaps from other apps. Without it, SVG text only (through /// egui and `clipboard_read`). diff --git a/crates/ui-egui/src/shortcuts.rs b/crates/ui-egui/src/shortcuts.rs index 63e311aeae..df87187a65 100644 --- a/crates/ui-egui/src/shortcuts.rs +++ b/crates/ui-egui/src/shortcuts.rs @@ -20,7 +20,7 @@ pub(crate) use held_tool::{HeldTool, note_tool_use}; use paste::unclip_chords; pub(crate) use paste::{PasteChord, paste_command}; pub(crate) use presentation::presentation_step; -use presentation::{escape_pair_id, escape_press, escape_resets_rotation, presentation_keys}; +use presentation::{escape_resets_rotation, presentation_keys}; #[cfg(test)] use typing::is_shortcut_chord; pub(crate) use typing::keep_marked_text; @@ -201,8 +201,6 @@ pub fn handle(app: &mut VectorcraftApp, ctx: &egui::Context) { crate::ime::controls_without_editor(app, ctx); return; } - // Taken before anything returns, so a press in a field or a dialog ends a pair of Escapes. - let mut escape_pair = escape_press(ctx); // Followed before anything returns, so a key typed in a field isn't taken for a paste. let textless_paste = ctx.input(|i| app.paste_chord.textless_paste(&i.events)); // A numeric field being scrubbed has the keyboard: Escape cancels the drag. @@ -238,7 +236,7 @@ pub fn handle(app: &mut VectorcraftApp, ctx: &egui::Context) { } if app.ui.screen_mode == 3 { crate::ime::controls_without_editor(app, ctx); - presentation_keys(app, ctx, escape_pair); + presentation_keys(app, ctx); return; } // Escape that cancels a ruler-origin drag or floating Tools move skips the tool and later Escape actions, @@ -268,7 +266,6 @@ pub fn handle(app: &mut VectorcraftApp, ctx: &egui::Context) { continue; } if k == Key::Escape && escape_ended_gesture { - remember_escape_pair(ctx, k, escape_pair); continue; } // A key the tool claims (Esc with a loaded place cursor) is only the tool's. @@ -285,7 +282,12 @@ pub fn handle(app: &mut VectorcraftApp, ctx: &egui::Context) { .unwrap_or(i.modifiers); crate::canvas::mods(m, false) }); + let ends = k == Key::Escape && app.session.tool_ends_on_escape(view); + let before = (k == Key::Escape && !ends).then(|| document_revision(app)); let r = app.session.tool_key(tk, mods, view); + // An Escape that ended something in the tool (a path being drawn, a selected point) ends + // nothing else. A hover highlight it clears does not count. + let tool_took = ends || before.is_some_and(|b| b != document_revision(app)); // Enter also takes what the tool asks of the UI: Rotate, Scale, Reflect and Shear open // their dialog with it. if claimed || (k == Key::Enter && !busy) { @@ -295,33 +297,9 @@ pub fn handle(app: &mut VectorcraftApp, ctx: &egui::Context) { ctx.input_mut(|i| i.consume_key(Modifiers::NONE, k)); ctx.input_mut(|i| i.consume_key(Modifiers::SHIFT, k)); } - if k == Key::Escape && !busy && !claimed && !escape_held_by_drag { - if app.session.active().is_some_and(|d| d.doc.pattern_edit.is_some()) { - let _ = app.run("object.pattern.done", json!({})); - } else if app.session.active().is_some_and(|d| d.isolation.is_some()) { - let _ = app.run("object.exitIsolation", json!({})); - } else if app.session.active().is_some_and(|d| d.global_edit.is_some()) { - let _ = app.run("select.globalEdit", json!({})); - } else if app.ui.flyout.is_some() { - app.ui.flyout = None; - } else if escape_pair.is_some_and(|second| escape_resets_rotation(app, ctx, second)) { - // Escape pressed twice resets a rotated view (with the Rotate View tool, once). - let _ = app.run("view.rotateReset", json!({})); - escape_pair = None; - } else if matches!(app.ui.screen_mode, 1 | 2) - && !egui::Popup::is_any_open(ctx) - && !text_focused_in_previous_frame(ctx) - && ctx.input(|i| { - i.events.iter().any(|e| { - matches!(e, egui::Event::Key { key: Key::Escape, pressed: true, repeat: false, modifiers, .. } if *modifiers == Modifiers::NONE) - }) - }) - { - let _ = app.run("view.screenMode", json!({ "mode": 0 })); - } + if k == Key::Escape && !busy && !claimed && !escape_held_by_drag && !tool_took { + escape_ends_one_thing(app, ctx); } - // An Escape that ended something can start a pair too. One that closed a popup cannot. - remember_escape_pair(ctx, k, escape_pair); if k == Key::Enter && !busy && !claimed { // Enter with a selection tool opens the Move dialog, as a double-click on its button // does. @@ -488,13 +466,45 @@ fn escape_ended_gesture(ctx: &egui::Context) -> bool { held } -fn remember_escape_pair(ctx: &egui::Context, key: Key, escape_pair: Option) { - if key == Key::Escape && escape_pair.is_some() && !egui::Popup::is_any_open(ctx) { - let now = ctx.input(|i| i.time); - ctx.data_mut(|d| d.insert_temp(escape_pair_id(), now)); +/// An Escape that no tool, field, popup or drag took ends the first of these that is on: pattern +/// editing, isolation mode, Global Edit, a tool flyout, a full screen mode and a rotated view. +fn escape_ends_one_thing(app: &mut VectorcraftApp, ctx: &egui::Context) { + if app.session.active().is_some_and(|d| d.doc.pattern_edit.is_some()) { + let _ = app.run("object.pattern.done", json!({})); + } else if app.session.active().is_some_and(|d| d.isolation.is_some()) { + let _ = app.run("object.exitIsolation", json!({})); + } else if app.session.active().is_some_and(|d| d.global_edit.is_some()) { + let _ = app.run("select.globalEdit", json!({})); + } else if app.ui.flyout.is_some() { + app.ui.flyout = None; + } else if app.session.tool_id() == "rotateView" && escape_resets_rotation(app, ctx) { + // With the Rotate View tool, the view resets before a full screen mode ends. + let _ = app.run("view.rotateReset", json!({})); + } else if matches!(app.ui.screen_mode, 1 | 2) + && !egui::Popup::is_any_open(ctx) + && !text_focused_in_previous_frame(ctx) + && ctx.input(|i| { + i.events.iter().any( + |e| matches!(e, egui::Event::Key { key: Key::Escape, pressed: true, repeat: false, modifiers, .. } if *modifiers == Modifiers::NONE), + ) + }) + { + let _ = app.run("view.screenMode", json!({ "mode": 0 })); + } else if escape_resets_rotation(app, ctx) { + // An Escape that has nothing else to end resets a rotated view. After one that ended + // something, the next one does, however long after it comes. A modified Escape does not + // leave a full screen mode, so it resets the view there. + let _ = app.run("view.rotateReset", json!({})); } } +/// What a tool's Escape can change besides what [`vectorcraft_engine::Session::tool_ends_on_escape`] +/// reports: the document's revision (edits and selection changes, such as the Curvature tool +/// letting go of a selected path's current point). +fn document_revision(app: &VectorcraftApp) -> Option { + app.session.active().map(|d| d.revision) +} + /// Dispatch unmodified text keys to command bindings or tools. fn single_key_shortcuts(app: &mut VectorcraftApp, ctx: &egui::Context) { // Single-key tool shortcuts (no Cmd/Ctrl/Alt). With a layout without Latin letters (Persian, diff --git a/crates/ui-egui/src/shortcuts/presentation.rs b/crates/ui-egui/src/shortcuts/presentation.rs index da746cbf5f..1c447d09e6 100644 --- a/crates/ui-egui/src/shortcuts/presentation.rs +++ b/crates/ui-egui/src/shortcuts/presentation.rs @@ -1,45 +1,18 @@ -use super::{Key, VectorcraftApp, is_modifier, json}; +use super::{Key, VectorcraftApp, json}; -/// The second press of Escape pressed twice comes less than this many seconds after the first. -const ESCAPE_PAIR_SECONDS: f64 = 1.0; - -/// The key of the last counted Escape's time in egui's temporary data. -pub(super) fn escape_pair_id() -> egui::Id { - egui::Id::unique("escape-pair") -} - -/// Reads this frame's presses for Escape pressed twice. `None` when the frame has no Escape press, or -/// has another key or pointer button press as well (a key repeat counts as another press, and the -/// modifier keys do not count). Otherwise, whether the last counted Escape came less than -/// [`ESCAPE_PAIR_SECONDS`] before. A press of Escape, another key or a pointer button removes the -/// last counted Escape's time. -pub(super) fn escape_press(ctx: &egui::Context) -> Option { - let (escape, other, now) = ctx.input(|i| { - let (mut escape, mut other) = (false, false); - for e in &i.events { - match e { - egui::Event::Key { key: Key::Escape, pressed: true, repeat: false, .. } => escape = true, - egui::Event::Key { key, pressed: true, .. } if !is_modifier(*key) => other = true, - egui::Event::PointerButton { pressed: true, .. } => other = true, - _ => {} - } - } - (escape, other, i.time) - }); - if !escape && !other { - return None; - } - let counted = ctx.data_mut(|d| d.remove_temp::(escape_pair_id())); - (escape && !other).then(|| counted.is_some_and(|t| now - t < ESCAPE_PAIR_SECONDS)) -} - -/// Does this Escape reset the view's rotation? It does when the view is rotated, no popup is open, -/// neither a ruler-origin drag nor a floating Tools move is ending, and the press is the second of -/// a pair (`second`) or the Rotate View tool is chosen. -pub(super) fn escape_resets_rotation(app: &VectorcraftApp, ctx: &egui::Context, second: bool) -> bool { +/// Does this Escape reset the view's rotation? The caller has checked that nothing earlier took +/// the press. It does when the view is rotated; no popup, modal window (a progress window, About) +/// or Appearance row popup is open; no text field had the keyboard in the last frame (egui takes +/// the focus away on Escape before this runs); no pointer button is held or let go in this frame +/// (a tab or panel drag takes the Escape, in its release frame too); and neither a ruler-origin +/// drag nor a floating Tools move is ending. +pub(super) fn escape_resets_rotation(app: &VectorcraftApp, ctx: &egui::Context) -> bool { app.view().is_some_and(|v| v.rotation != 0.0) - && (second || app.session.tool_id() == "rotateView") && !egui::Popup::is_any_open(ctx) + && !crate::panel_docking::modal_open(app, ctx) + && app.ui.transient_panel.is_none() + && !super::text_focused_in_previous_frame(ctx) + && !ctx.input(|i| i.pointer.any_down() || i.pointer.any_released()) && !crate::canvas::ruler_origin_dragging(ctx) && !crate::tools_float::escape_cancelled_move(ctx) } @@ -48,7 +21,7 @@ pub(super) fn escape_resets_rotation(app: &VectorcraftApp, ctx: &egui::Context, /// the previous and the next artboard ([`presentation_step`]). Every other key press, the text it /// types and the clipboard keys are removed from the input, so no shortcut, tool or field acts on /// them. The macOS menu bar's key equivalents arrive as key presses too ([`crate::native_menu`]). -pub(super) fn presentation_keys(app: &mut VectorcraftApp, ctx: &egui::Context, escape_pair: Option) { +pub(super) fn presentation_keys(app: &mut VectorcraftApp, ctx: &egui::Context) { let (mut leave, mut steps) = (false, vec![]); ctx.input_mut(|i| { i.events.retain(|e| match e { @@ -80,11 +53,6 @@ pub(super) fn presentation_keys(app: &mut VectorcraftApp, ctx: &egui::Context, e } if leave { let _ = app.run("view.presentation", json!({})); - // The Escape that left the mode can start a pair, as in `handle`. - if escape_pair.is_some() && !egui::Popup::is_any_open(ctx) { - let now = ctx.input(|i| i.time); - ctx.data_mut(|d| d.insert_temp(escape_pair_id(), now)); - } } } diff --git a/crates/ui-egui/src/tests.rs b/crates/ui-egui/src/tests.rs index 2593115f60..261a250542 100644 --- a/crates/ui-egui/src/tests.rs +++ b/crates/ui-egui/src/tests.rs @@ -39,6 +39,7 @@ mod saveext; mod screenmode; mod screenshots; mod script_check; +mod script_run; mod scrub; mod selectall; mod selectescape; diff --git a/crates/ui-egui/src/tests/contextmenu.rs b/crates/ui-egui/src/tests/contextmenu.rs index 26e04961bb..b443d84586 100644 --- a/crates/ui-egui/src/tests/contextmenu.rs +++ b/crates/ui-egui/src/tests/contextmenu.rs @@ -291,6 +291,46 @@ fn selected_type_has_apply_numbers() { assert_eq!(text.para_at(0).list.and_then(|l| l.number), Some(vectorcraft_doc::text::NumberStyle::Arabic)); } +/// A right-click on type has Spelling › Auto Spell Check, which turns it on or off as Edit › +/// Spelling does (helpx: Check and correct spelling, "Turn on Auto Spell Check"). The context menu +/// draws no check marks, but this submenu holds only the toggle, so it shows whether it is on; +/// other submenus stay without the room for one. Other art has no Spelling submenu. +#[test] +fn right_click_on_type_turns_auto_spell_check_on_and_off() { + let mut app = app(); + let r = rect(&mut app, 200.0, 150.0); + let t = NodeId(app.run("text.create", json!({"x": 20, "y": 60, "text": "Hello", "size": 24})).unwrap()["id"].as_u64().unwrap()); + app.run("select.none", json!({})).unwrap(); + let ctx = egui::Context::default(); + frame(&mut app, &ctx, vec![]); + let p = screen(&app, 250.0, 200.0); + assert!(!has(&click(&mut app, &ctx, p, PointerButton::Secondary), "Spelling"), "a rectangle has no Spelling submenu"); + assert_eq!(app.session.active().unwrap().selection.objects, [r]); + let away = screen(&app, 390.0, 290.0); + click(&mut app, &ctx, away, PointerButton::Primary); + // Right-click the type, open Spelling: Auto Spell Check, not checked. + let open_spelling = |app: &mut VectorcraftApp| { + let p = word_at(app, t, 0, 5); + let texts = click(app, &ctx, p, PointerButton::Secondary); + assert_eq!(app.session.active().unwrap().selection.objects, [t], "the type right-clicked is selected"); + frame(app, &ctx, vec![Event::PointerMoved(at(&texts, "Spelling"))]); + frame(app, &ctx, vec![]) + }; + let texts = open_spelling(&mut app); + assert!(texts.iter().any(|(s, _)| s == " Auto Spell Check"), "unchecked, with the room for a check mark: {texts:?}"); + assert!(texts.iter().any(|(s, _)| s == "Transform"), "other items have no gutter: {texts:?}"); + // Agents see it under the Spelling path. + let e = menus::context_entries(&app).into_iter().find(|e| e.command.as_deref() == Some("edit.autoSpellCheck")).expect("Auto Spell Check"); + assert_eq!((e.path.as_slice(), e.label.as_str()), (&["Spelling".to_string()][..], "Auto Spell Check")); + let texts = click(&mut app, &ctx, at(&texts, " Auto Spell Check"), PointerButton::Primary); + assert!(app.ui.view.auto_spell_check, "turned on"); + assert!(!has(&texts, "Spelling"), "the menu closed: {texts:?}"); + let texts = open_spelling(&mut app); + assert!(texts.iter().any(|(s, _)| s == "✓ Auto Spell Check"), "checked: {texts:?}"); + click(&mut app, &ctx, at(&texts, "✓ Auto Spell Check"), PointerButton::Primary); + assert!(!app.ui.view.auto_spell_check, "turned off"); +} + /// The members of the overlap area of Intertwine group `g` at (x, y), in the order they are drawn /// there, bottom first. fn intertwine_order(app: &VectorcraftApp, g: NodeId, x: f64, y: f64) -> Vec { diff --git a/crates/ui-egui/src/tests/rotateview.rs b/crates/ui-egui/src/tests/rotateview.rs index 8f477894a0..2f98a3f3b1 100644 --- a/crates/ui-egui/src/tests/rotateview.rs +++ b/crates/ui-egui/src/tests/rotateview.rs @@ -30,6 +30,13 @@ fn with_document() -> VectorcraftApp { app } +/// Send a control request and keep its success/error value for protocol assertions. +fn control_response(app: &mut VectorcraftApp, ctx: &egui::Context, method: &str, params: Value) -> Value { + let (request, _) = crate::control::ControlRequest::new(method, params); + let crate::control::Outcome::Done(reply) = crate::control::handle(app, ctx, &request) else { panic!("not done") }; + reply +} + /// Returns the labels of the View › Rotate View items that are checked. fn checked(app: &VectorcraftApp) -> Vec<&'static str> { ANGLES.iter().filter(|(_, a)| menus::checked(app, "view.rotate", &json!({ "angle": a })) == Some(true)).map(|(l, _)| *l).collect() @@ -55,6 +62,157 @@ fn view_rotate_turns_the_view_to_any_angle() { assert_eq!(empty.run("view.rotate", json!({"angle": 30})).unwrap_err(), "no document"); } +/// MCP's `pointer_gesture` reaches `ui.pointer`: view tools must turn the canvas there too, +/// rather than silently sending the gesture to the engine's no-op tool. +#[test] +fn control_rotate_view_gesture_turns_the_canvas_and_reset_restores_it() { + let mut app = with_document(); + let ctx = egui::Context::default(); + app.canvas_rect = Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(800.0, 600.0))); + let view = app.view_mut().unwrap(); + view.center = vectorcraft_geom::Point::new(200.0, 150.0); + view.zoom = 1.0; + let revision = app.session.active().unwrap().revision; + let send = super::synthetic::control; + send(&mut app, &ctx, "ui.tool.select", json!({"tool": "rotateView"})); + send(&mut app, &ctx, "ui.pointer", json!({"events": [{"kind": "down", "x": 300, "y": 150}]})); + let mut frame = ctx.run_ui(Default::default(), |_| {}); + frame.textures_delta.clear(); + send( + &mut app, + &ctx, + "ui.pointer", + json!({"events": [ + {"kind": "drag", "x": 200, "y": 250}, + {"kind": "up", "x": 200, "y": 250} + ]}), + ); + let view = app.view().unwrap(); + assert!((view.rotation - 90.0).abs() < 1e-3, "{}", view.rotation); + assert_eq!(view.center, vectorcraft_geom::Point::new(200.0, 150.0)); + assert_eq!(view.zoom, 1.0); + assert_eq!(app.session.active().unwrap().revision, revision, "navigation does not edit the document"); + let reset = control_response(&mut app, &ctx, "engine.execute", json!({"command": "view.rotateReset", "params": {}})); + assert_eq!(reset["ok"], true); + assert!(reset["result"].is_null()); + assert_eq!(app.view().unwrap().rotation, 0.0); +} + +/// Repeated document points stay fixed across requests, including Shift snapping from a turned view. +#[test] +fn control_rotate_view_keeps_press_coordinates_and_shift_snapping_across_requests() { + let mut app = with_document(); + let ctx = egui::Context::default(); + app.canvas_rect = Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(800.0, 600.0))); + let view = app.view_mut().unwrap(); + view.center = vectorcraft_geom::Point::new(200.0, 150.0); + view.zoom = 1.0; + view.rotation = 30.0; + let send = super::synthetic::control; + send(&mut app, &ctx, "ui.tool.select", json!({"tool": "rotateView"})); + send(&mut app, &ctx, "ui.pointer", json!({"events": [{"kind": "down", "x": 300, "y": 150}]})); + let angle = 20_f64.to_radians(); + let (x, y) = (200.0 + 100.0 * angle.cos(), 150.0 + 100.0 * angle.sin()); + for _ in 0..2 { + send(&mut app, &ctx, "ui.pointer", json!({"mods": {"shift": true}, "events": [{"kind": "drag", "x": x, "y": y}]})); + assert_eq!(app.view().unwrap().rotation, 45.0, "the same document point does not turn again as the view changes"); + } + send(&mut app, &ctx, "ui.pointer", json!({"events": [{"kind": "up", "x": x, "y": y}]})); + assert_eq!(app.view().unwrap().rotation, 45.0); +} + +/// Invalid coordinates and document changes cannot turn a different view. +#[test] +fn control_rotate_view_rejects_nonfinite_positions_and_a_changed_document() { + let mut app = with_document(); + let ctx = egui::Context::default(); + app.canvas_rect = Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(800.0, 600.0))); + let send = super::synthetic::control; + send(&mut app, &ctx, "ui.tool.select", json!({"tool": "rotateView"})); + let (req, _) = crate::control::ControlRequest::new("ui.pointer", json!({"events": [{"kind": "down", "x": 1e300, "y": 0}]})); + let crate::control::Outcome::Done(reply) = crate::control::handle(&mut app, &ctx, &req) else { panic!("not done") }; + assert_eq!(reply["ok"], false); + assert_eq!(app.view().unwrap().rotation, 0.0); + send(&mut app, &ctx, "ui.pointer", json!({"events": [{"kind": "down", "x": 300, "y": 150}]})); + app.run("file.new", json!({})).unwrap(); + let (req, _) = crate::control::ControlRequest::new("ui.pointer", json!({"events": [{"kind": "drag", "x": 200, "y": 250}]})); + let crate::control::Outcome::Done(reply) = crate::control::handle(&mut app, &ctx, &req) else { panic!("not done") }; + assert_eq!(reply["ok"], false); + assert_eq!(app.view().unwrap().rotation, 0.0); +} + +/// An invalid packet leaves the angle unchanged and requires a fresh press, including errors +/// after an otherwise valid drag and malformed releases or hovers. +#[test] +fn control_rotate_view_rejects_malformed_packets_without_leaving_a_press() { + let drag = json!({"kind": "drag", "x": 200, "y": 250}); + for packet in [ + json!({"events": [drag.clone(), {"kind": "drag", "y": 250}]}), + json!({"events": [drag.clone(), {"kind": "drag", "x": "200", "y": 250}]}), + json!({"events": [drag.clone(), {"kind": "drag", "x": 200, "y": 250, "mods": {"shift": "yes"}}]}), + json!({"mods": "shift", "events": [drag.clone()]}), + json!({"events": [drag.clone(), {"kind": "drag", "x": 200, "y": 250, "mods": {"unknown": true}}]}), + json!({"events": [drag.clone(), {"kind": "drag", "x": 1e300, "y": 250}]}), + json!({"events": [drag.clone(), {"kind": "up", "x": 1e300, "y": 250}]}), + json!({"events": [drag.clone(), {"kind": "move", "x": 1e300, "y": 250}]}), + json!({"events": [drag.clone(), {"kind": "doubleclick", "x": 1e300, "y": 250}]}), + json!({"events": [drag.clone(), {"kind": "wiggle", "x": 200, "y": 250}]}), + json!({"events": [drag.clone(), {"kind": "drag", "x": 200, "y": 250, "space": "window"}]}), + json!({"events": null}), + ] { + let mut app = with_document(); + let ctx = egui::Context::default(); + app.canvas_rect = Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(800.0, 600.0))); + let view = app.view_mut().unwrap(); + view.center = vectorcraft_geom::Point::new(200.0, 150.0); + view.zoom = 1.0; + super::synthetic::control(&mut app, &ctx, "ui.tool.select", json!({"tool": "rotateView"})); + super::synthetic::control(&mut app, &ctx, "ui.pointer", json!({"events": [{"kind": "down", "x": 300, "y": 150}]})); + let reply = control_response(&mut app, &ctx, "ui.pointer", packet.clone()); + assert_eq!(reply["ok"], false, "{packet}: {reply}"); + assert_eq!(app.view().unwrap().rotation, 0.0, "{packet}"); + let resume = control_response(&mut app, &ctx, "ui.pointer", json!({"events": [drag.clone()]})); + assert_eq!(resume["ok"], false, "a failed packet cancels its press: {packet}"); + assert_eq!(app.view().unwrap().rotation, 0.0); + } +} + +/// Screen-space gestures survive frames, stop on release or a tool change, and start afresh +/// from the current angle. A press at the pivot uses the same finite convention as the mouse. +#[test] +fn control_rotate_view_screen_events_require_a_live_press() { + let mut app = with_document(); + let ctx = egui::Context::default(); + app.canvas_rect = Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(800.0, 600.0))); + let view = app.view_mut().unwrap(); + view.center = vectorcraft_geom::Point::new(1200.0, 900.0); + view.zoom = 2.0; + let send = super::synthetic::control; + send(&mut app, &ctx, "ui.tool.select", json!({"tool": "rotateView"})); + let down = json!({"events": [{"kind": "down", "x": 500, "y": 300, "space": "screen"}]}); + let drag = json!({"events": [{"kind": "drag", "x": 400, "y": 400, "space": "screen"}]}); + assert_eq!(control_response(&mut app, &ctx, "ui.pointer", drag.clone())["ok"], false); + send(&mut app, &ctx, "ui.pointer", down.clone()); + let mut frame = ctx.run_ui(Default::default(), |_| {}); + frame.textures_delta.clear(); + send(&mut app, &ctx, "ui.pointer", drag.clone()); + assert!((app.view().unwrap().rotation - 90.0).abs() < 1e-3); + send(&mut app, &ctx, "ui.pointer", json!({"events": [{"kind": "up", "x": 400, "y": 400, "space": "screen"}]})); + assert_eq!(control_response(&mut app, &ctx, "ui.pointer", drag.clone())["ok"], false, "release ends the press"); + send(&mut app, &ctx, "ui.pointer", down.clone()); + send(&mut app, &ctx, "ui.tool.select", json!({"tool": "selection"})); + send(&mut app, &ctx, "ui.tool.select", json!({"tool": "rotateView"})); + assert_eq!(control_response(&mut app, &ctx, "ui.pointer", drag.clone())["ok"], false, "a tool change ends the press"); + send(&mut app, &ctx, "ui.pointer", down); + send(&mut app, &ctx, "ui.pointer", drag); + assert!((app.view().unwrap().rotation.abs() - 180.0).abs() < 1e-3, "a new press starts at the current angle"); + let before = app.view().unwrap().rotation; + send(&mut app, &ctx, "ui.pointer", json!({"events": [{"kind": "down", "x": 400, "y": 300, "space": "screen"}]})); + send(&mut app, &ctx, "ui.pointer", json!({"events": [{"kind": "drag", "x": 500, "y": 300, "space": "screen"}]})); + assert!(app.view().unwrap().rotation.is_finite()); + assert!((app.view().unwrap().rotation - before).abs() < 1e-3); +} + #[test] fn the_view_menu_lists_the_status_bar_angles_and_checks_the_current_one() { let mut app = with_document(); @@ -262,80 +420,259 @@ fn key(key: egui::Key, repeat: bool) -> Vec { [true, false].map(|pressed| egui::Event::Key { key, physical_key: None, pressed, repeat, modifiers: Default::default() }).to_vec() } -/// The second of two Escape presses less than a second apart resets a rotated view. A press of -/// another key or a pointer button between them, or a longer wait, ends the pair. Shift does not. +fn selected(app: &VectorcraftApp) -> usize { + app.session.active().unwrap().selection.objects.len() +} + +/// One Escape resets a rotated view when it has nothing else to end, with or without a selected +/// object, which stays selected. Shift held down with it (as after a Space+Shift drag) does not +/// change that, and the repeats of a held Escape do nothing more. #[test] -fn escape_pressed_twice_resets_a_rotated_view() { +fn one_escape_resets_a_rotated_view() { let mut w = Window::new(); w.escape(0.0); - assert_eq!(w.rotation(), 30.0, "one Escape"); + assert_eq!(w.rotation(), 0.0, "one Escape with nothing selected"); w.escape(0.5); - assert_eq!(w.rotation(), 0.0, "a second Escape 0.5 s later"); - w.escape(0.5); - assert_eq!(w.rotation(), 0.0, "a third Escape leaves the view at 0°"); + assert_eq!(w.rotation(), 0.0, "a second Escape leaves the view at 0°"); let mut w = Window::new(); - let empty = w.app.canvas_rect.unwrap().left_top() + egui::vec2(20.0, 20.0); + w.app.run("shape.rectangle", json!({"x": 20, "y": 20, "width": 40, "height": 40})).unwrap(); + w.after(0.0, vec![]); + assert_eq!(selected(&w.app), 1); w.escape(0.0); - w.click(0.2, egui::PointerButton::Primary, empty); - w.escape(0.2); - assert_eq!(w.rotation(), 30.0, "a click between the two"); - let mut w = Window::new(); - w.escape(0.0); - w.after(0.2, key(egui::Key::ArrowRight, false)); - w.escape(0.2); - assert_eq!(w.rotation(), 30.0, "an arrow key between the two"); - let mut w = Window::new(); - w.escape(0.0); - w.after(0.2, key(egui::Key::ShiftLeft, false)); - w.escape(0.2); - assert_eq!(w.rotation(), 0.0, "a Shift press between the two"); + assert_eq!((w.rotation(), selected(&w.app)), (0.0, 1), "one Escape with a selected object, which stays selected"); let mut w = Window::new(); - w.escape(0.0); - w.escape(2.0); - assert_eq!(w.rotation(), 30.0, "two Escapes 2 s apart"); - w.escape(0.5); - assert_eq!(w.rotation(), 0.0, "the later of them starts a pair"); + let shifted = [true, false].map(|pressed| egui::Event::Key { + key: egui::Key::Escape, + physical_key: None, + pressed, + repeat: false, + modifiers: egui::Modifiers::SHIFT, + }); + w.after(0.0, shifted.to_vec()); + assert_eq!(w.rotation(), 0.0, "Shift+Escape"); - // A held Escape repeats: the repeats are not a second press. let mut w = Window::new(); w.after(0.0, vec![key(egui::Key::Escape, false)[0].clone()]); + assert_eq!(w.rotation(), 0.0, "the press of a held Escape"); + w.app.run("view.rotate", json!({"angle": 30})).unwrap(); for _ in 0..5 { w.after(0.1, vec![key(egui::Key::Escape, true)[0].clone()]); } w.after(0.1, vec![key(egui::Key::Escape, false)[1].clone()]); - assert_eq!(w.rotation(), 30.0, "Escape held down"); + assert_eq!(w.rotation(), 30.0, "its repeats"); + + let mut w = Window::new(); + w.app.select_tool("rotateView"); + w.escape(0.0); + assert_eq!(w.rotation(), 0.0, "one Escape with the Rotate View tool"); + + // A hover highlight that the Escape clears does not count as something it ends. + let mut w = Window::new(); + w.app.run("shape.rectangle", json!({"x": 150, "y": 100, "width": 120, "height": 80})).unwrap(); + // The new object is the selection, to be put on the path under the pointer. + w.app.run("shape.rectangle", json!({"x": 20, "y": 20, "width": 40, "height": 40})).unwrap(); + w.app.select_tool("objectsOnPath"); + let view = w.app.view_info(); + let over = vectorcraft_tools::PointerEvent::new(vectorcraft_tools::PointerKind::Move, 150.0, 140.0); + w.app.session.pointer(&over, view).unwrap(); + assert!(!w.app.session.overlays(view).is_empty(), "Objects on Path highlights the path under the pointer"); + w.escape(0.0); + assert_eq!(w.rotation(), 0.0, "one Escape with Objects on Path hovering"); } -/// The first Escape of a pair may end something, such as isolation mode. With the Rotate View -/// tool, one Escape resets the view. +/// An Escape that ends something, such as isolation mode, leaves the view as it is. The next +/// Escape resets it, however long after it comes and whatever is clicked or pressed in between. #[test] -fn escape_after_ending_isolation_or_with_the_rotate_view_tool_resets_the_view() { +fn escape_after_ending_isolation_resets_the_view() { + let isolated_window = || { + let mut w = Window::new(); + w.app.run("shape.rectangle", json!({"x": 20, "y": 20, "width": 40, "height": 40})).unwrap(); + w.app.run("shape.rectangle", json!({"x": 80, "y": 20, "width": 40, "height": 40})).unwrap(); + w.app.run("select.all", json!({})).unwrap(); + w.app.run("object.group", json!({})).unwrap(); + menus::invoke(&mut w.app, "object.isolate", json!({})); + w.after(0.0, vec![]); + w + }; + let isolated = |w: &Window| w.app.session.active().unwrap().isolation.is_some(); + let mut w = isolated_window(); + assert!(isolated(&w)); + w.escape(0.0); + assert_eq!((isolated(&w), w.rotation()), (false, 30.0), "the first Escape leaves isolation mode"); + w.escape(5.0); + assert_eq!(w.rotation(), 0.0, "the second resets the view 5 s later"); + + let mut w = isolated_window(); + let empty = w.app.canvas_rect.unwrap().left_top() + egui::vec2(20.0, 20.0); + w.escape(0.0); + assert_eq!((isolated(&w), w.rotation()), (false, 30.0)); + w.click(2.0, egui::PointerButton::Primary, empty); + w.after(0.5, key(egui::Key::ArrowRight, false)); + w.escape(3.0); + assert_eq!(w.rotation(), 0.0, "after a click and an arrow key between the two"); +} + +/// An Escape that ends the path the Pen, the Smart Pen or the Curvature tool is drawing leaves the +/// view as it is, with the rubber band shown or not; the next Escape resets it. +#[test] +fn escape_that_ends_a_path_being_drawn_keeps_the_rotation() { + for (tool, rubber_band) in [("pen", true), ("pen", false), ("smartPen", true), ("smartPen", false), ("curvature", true)] { + let mut w = Window::new(); + w.app.session.prefs.pen_rubber_band = rubber_band; + w.app.select_tool(tool); + let c = w.app.canvas_rect.unwrap().center(); + w.click(0.0, egui::PointerButton::Primary, c); + w.click(0.1, egui::PointerButton::Primary, c + egui::vec2(60.0, 10.0)); + w.after(0.1, vec![egui::Event::PointerMoved(c + egui::vec2(60.0, 80.0))]); + assert!(w.app.session.tool_ends_on_escape(w.app.view_info()), "{tool}: a path is being drawn"); + w.escape(0.2); + assert_eq!(w.rotation(), 30.0, "{tool}, rubber band {rubber_band}: the Escape that ends the path"); + assert!(!w.app.session.tool_ends_on_escape(w.app.view_info()), "{tool}: the path is ended"); + w.escape(3.0); + assert_eq!(w.rotation(), 0.0, "{tool}, rubber band {rubber_band}: the next Escape"); + } +} + +/// In isolation mode, an Escape that ends the Pen's path ends only the path: the next Escape leaves +/// isolation mode, and the one after it resets the view. +#[test] +fn escape_ends_one_thing_at_a_time() { let mut w = Window::new(); w.app.run("shape.rectangle", json!({"x": 20, "y": 20, "width": 40, "height": 40})).unwrap(); w.app.run("shape.rectangle", json!({"x": 80, "y": 20, "width": 40, "height": 40})).unwrap(); w.app.run("select.all", json!({})).unwrap(); w.app.run("object.group", json!({})).unwrap(); menus::invoke(&mut w.app, "object.isolate", json!({})); + w.after(0.0, vec![]); let isolated = |w: &Window| w.app.session.active().unwrap().isolation.is_some(); assert!(isolated(&w)); - w.escape(0.0); - assert_eq!((isolated(&w), w.rotation()), (false, 30.0), "the first Escape leaves isolation mode"); - w.escape(0.5); - assert_eq!(w.rotation(), 0.0, "the second resets the view"); - - let mut w = Window::new(); - w.app.select_tool("rotateView"); - w.escape(0.0); - assert_eq!(w.rotation(), 0.0, "one Escape with the Rotate View tool"); + w.app.select_tool("pen"); + let c = w.app.canvas_rect.unwrap().center(); + w.click(0.0, egui::PointerButton::Primary, c); + w.click(0.1, egui::PointerButton::Primary, c + egui::vec2(60.0, 10.0)); + assert!(w.app.session.tool_ends_on_escape(w.app.view_info()), "a path is being drawn"); + w.escape(0.2); + assert!(!w.app.session.tool_ends_on_escape(w.app.view_info()), "the first Escape ends the path"); + assert_eq!((isolated(&w), w.rotation()), (true, 30.0), "and only the path"); + w.escape(0.2); + assert_eq!((isolated(&w), w.rotation()), (false, 30.0), "the second leaves isolation mode"); + w.escape(0.2); + assert_eq!(w.rotation(), 0.0, "the third resets the view"); } -/// An Escape that closes a popup (the status bar's angle menu, the canvas context menu) does not -/// count, so the Escape after it leaves the view as it is. An Escape while the ruler origin is -/// dragged does not reset the view either, but it counts as the first Escape of a pair. +/// The Escape that leaves the Artboard tool leaves the view as it is; the next resets it. #[test] -fn escape_after_closing_a_popup_or_during_a_ruler_origin_drag_keeps_the_rotation() { +fn escape_after_leaving_the_artboard_tool_resets_the_view() { + let mut w = Window::new(); + w.app.select_tool("artboard"); + w.escape(0.0); + assert_eq!((w.app.session.tool_id(), w.rotation()), ("selection", 30.0), "the first Escape leaves the Artboard tool"); + w.escape(5.0); + assert_eq!(w.rotation(), 0.0, "the next resets the view"); +} + +/// An Escape that a dialog or a full screen mode takes leaves the view as it is; the next resets it. +#[test] +fn escape_in_a_dialog_or_a_full_screen_mode_keeps_the_rotation() { + let mut w = Window::new(); + menus::invoke(&mut w.app, "view.rotate", json!({})); + w.after(0.0, vec![]); + assert!(w.app.ui.dialog.is_some(), "Rotate View asks for an angle"); + w.escape(0.0); + assert_eq!((w.app.ui.dialog.is_none(), w.rotation()), (true, 30.0), "Escape closes the dialog"); + w.escape(0.5); + assert_eq!(w.rotation(), 0.0, "the next Escape"); + + for mode in [1, 2] { + let mut w = Window::new(); + w.app.ui.screen_mode = mode; + w.after(0.0, vec![]); + w.escape(0.0); + assert_eq!((w.app.ui.screen_mode, w.rotation()), (0, 30.0), "Escape leaves screen mode {mode}"); + w.escape(0.5); + assert_eq!(w.rotation(), 0.0, "the next Escape after screen mode {mode}"); + + // Shift+Escape does not leave a full screen mode, so it resets the view there. + let mut w = Window::new(); + w.app.ui.screen_mode = mode; + w.after(0.0, vec![]); + let shifted = [true, false].map(|pressed| egui::Event::Key { + key: egui::Key::Escape, + physical_key: None, + pressed, + repeat: false, + modifiers: egui::Modifiers::SHIFT, + }); + w.after(0.0, shifted.to_vec()); + assert_eq!((w.app.ui.screen_mode, w.rotation()), (mode, 0.0), "Shift+Escape in screen mode {mode}"); + } + + let mut w = Window::new(); + w.app.run("view.presentation", json!({})).unwrap(); + w.after(0.0, vec![]); + assert_eq!(w.app.ui.screen_mode, 3, "Presentation Mode"); + w.escape(0.0); + assert_eq!((w.app.ui.screen_mode != 3, w.rotation()), (true, 30.0), "Escape leaves Presentation Mode"); + w.escape(0.5); + assert_eq!(w.rotation(), 0.0, "the next Escape after Presentation Mode"); +} + +/// An Escape while About or an Appearance row's popup is open, or while a pointer button is held +/// outside the canvas (a scroll bar, a tab or a panel being dragged) or let go in the same frame, +/// leaves the view as it is. +#[test] +fn escape_with_a_window_open_or_a_button_held_keeps_the_rotation() { + let mut w = Window::new(); + w.app.ui.about = true; + w.after(0.0, vec![]); + w.escape(0.0); + assert_eq!(w.rotation(), 30.0, "an Escape with About open"); + + // An Appearance row's popup (here, the Stroke panel's) closes on Escape as the frame is drawn. + let mut w = Window::new(); + w.app.ui.transient_panel = Some("stroke".into()); + w.escape(0.0); + assert_eq!(w.rotation(), 30.0, "an Escape with an Appearance row's popup open"); + + let mut w = Window::new(); + let bar = w.app.canvas_rect.unwrap().right_center() + egui::vec2(4.0, 0.0); + let button = |pressed| egui::Event::PointerButton { pos: bar, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() }; + w.after(0.0, vec![egui::Event::PointerMoved(bar), button(true)]); + w.escape(0.1); + assert_eq!(w.rotation(), 30.0, "an Escape with the button held"); + let mut release = vec![button(false)]; + release.extend(key(egui::Key::Escape, false)); + w.after(0.1, release); + assert_eq!(w.rotation(), 30.0, "an Escape in the frame the button is let go"); + w.escape(0.1); + assert_eq!(w.rotation(), 0.0, "an Escape after the release"); +} + +/// An Escape in a text field ends the editing and leaves the view as it is. +#[test] +fn escape_in_a_text_field_keeps_the_rotation() { + let mut w = Window::new(); + w.ctx.enable_accesskit(); + let out = w.after(0.0, vec![]); + let tree = out.platform_output.accesskit_update.expect("the window's accessibility tree"); + let field = tree.nodes.iter().find(|(_, node)| node.role() == egui::accesskit::Role::TextInput).map(|(id, _)| *id).expect("a text field"); + let field = w + .ctx + .viewport(|vp| vp.prev_pass.widgets.layers().flat_map(|(_, ws)| ws.iter()).find(|r| r.id.accesskit_id() == field).copied()) + .expect("the text field's widget"); + w.ctx.memory_mut(|m| m.request_focus(field.id)); + w.after(0.0, vec![]); + assert!(w.ctx.egui_wants_keyboard_input(), "the field has the keyboard"); + w.escape(0.0); + assert_eq!(w.rotation(), 30.0, "the Escape in the field"); +} + +/// An Escape that closes a popup (the status bar's angle menu, the canvas context menu) or ends a +/// drag of the ruler origin leaves the view as it is; the next Escape resets it. +#[test] +fn escape_that_closes_a_popup_or_ends_a_ruler_origin_drag_keeps_the_rotation() { let mut w = Window::new(); // Find the actual combo by its accessible name, which is present in both build profiles; // `Id`'s debug source (including "rot-combo") only exists with debug assertions enabled. @@ -354,8 +691,9 @@ fn escape_after_closing_a_popup_or_during_a_ruler_origin_drag_keeps_the_rotation assert!(craft_ui::ComboBox::is_open(&w.ctx, combo.id), "the angle menu is open"); w.escape(0.2); assert!(!egui::Popup::is_any_open(&w.ctx), "Escape closes it"); + assert_eq!(w.rotation(), 30.0, "the Escape that closes the angle menu"); w.escape(0.2); - assert_eq!(w.rotation(), 30.0, "an Escape after the angle menu closed"); + assert_eq!(w.rotation(), 0.0, "the next Escape"); let mut w = Window::new(); w.click(0.0, egui::PointerButton::Secondary, w.app.canvas_rect.unwrap().center()); @@ -363,8 +701,9 @@ fn escape_after_closing_a_popup_or_during_a_ruler_origin_drag_keeps_the_rotation assert!(egui::Popup::is_any_open(&w.ctx), "a right click opens the context menu"); w.escape(0.2); assert!(!egui::Popup::is_any_open(&w.ctx), "Escape closes it"); + assert_eq!(w.rotation(), 30.0, "the Escape that closes the context menu"); w.escape(0.2); - assert_eq!(w.rotation(), 30.0, "an Escape after the context menu closed"); + assert_eq!(w.rotation(), 0.0, "the next Escape"); // With the Rotate View tool, the Escape that closes the menu leaves the view as it is too. let mut w = Window::new(); w.app.select_tool("rotateView"); @@ -391,5 +730,5 @@ fn escape_after_closing_a_popup_or_during_a_ruler_origin_drag_keeps_the_rotation assert_eq!(w.rotation(), 30.0, "two Escapes while the ruler origin is dragged"); w.after(0.1, vec![button(to, false)]); w.escape(0.2); - assert_eq!(w.rotation(), 0.0, "an Escape after the drag ends pairs with the last one"); + assert_eq!(w.rotation(), 0.0, "an Escape after the drag ends"); } diff --git a/crates/ui-egui/src/tests/screenmode.rs b/crates/ui-egui/src/tests/screenmode.rs index 56bcca519a..3154ccb6d9 100644 --- a/crates/ui-egui/src/tests/screenmode.rs +++ b/crates/ui-egui/src/tests/screenmode.rs @@ -677,7 +677,7 @@ fn a_tool_flyout_takes_escape_before_full_screen() { } #[test] -fn a_rotation_pair_exits_full_screen_then_resets_with_selection_tool() { +fn escape_exits_full_screen_then_resets_the_rotation_with_selection_tool() { for mode in [1, 2] { let ctx = egui::Context::default(); let mut app = in_screen_mode(&ctx, mode); @@ -686,7 +686,7 @@ fn a_rotation_pair_exits_full_screen_then_resets_with_selection_tool() { assert_eq!(app.ui.screen_mode, 0, "first Escape in mode {mode}"); assert_eq!(app.view().unwrap().rotation, 30.0); frame(&mut app, &ctx, escape()); - assert_eq!(app.view().unwrap().rotation, 0.0, "second Escape after mode {mode}"); + assert_eq!(app.view().unwrap().rotation, 0.0, "the next Escape after mode {mode}"); } } diff --git a/crates/ui-egui/src/tests/script_check.rs b/crates/ui-egui/src/tests/script_check.rs index ccaa6c7a8c..0ff703eb3b 100644 --- a/crates/ui-egui/src/tests/script_check.rs +++ b/crates/ui-egui/src/tests/script_check.rs @@ -46,7 +46,7 @@ fn file_scripts_holds_check_script_above_other_script() { let (_, file) = tree.iter().find(|(t, _)| *t == "File").unwrap(); let scripts = file.iter().find_map(|i| if let menus::Item::Sub("Scripts", items) = i { Some(items) } else { None }).unwrap(); assert!( - matches!(scripts.as_slice(), [menus::Item::Cmd("Check Script…", "ui.checkScript", _), menus::Item::Todo("Other Script…", _)]), + matches!(scripts.as_slice(), [menus::Item::Cmd("Check Script…", "ui.checkScript", _), menus::Item::Cmd("Other Script…", "ui.runScript", _)]), "{scripts:?}" ); } diff --git a/crates/ui-egui/src/tests/script_run.rs b/crates/ui-egui/src/tests/script_run.rs new file mode 100644 index 0000000000..08ac8e1917 --- /dev/null +++ b/crates/ui-egui/src/tests/script_run.rs @@ -0,0 +1,283 @@ +//! File › Scripts › Other Script… (`ui.runScript`): the chooser, the warning and its preference, +//! a run advanced frame by frame, Stop, and the questions a run and quitting ask. + +use serde_json::{Value, json}; +use vectorcraft_engine::Session; + +use crate::{VectorcraftApp, dialogs, menus, script_runs}; + +fn app() -> VectorcraftApp { + let mut app = VectorcraftApp::new(Session::new(), crate::Services::default()); + app.run("file.new", json!({})).unwrap(); + app +} + +fn folder(name: &str) -> std::path::PathBuf { + let dir = std::env::temp_dir().join(format!("vc-script-run-ui-{name}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + dir +} + +fn objects(app: &VectorcraftApp) -> usize { + app.session.doc().unwrap().doc.layers.iter().map(|l| l.children().map_or(0, Vec::len)).sum() +} + +fn finish(app: &mut VectorcraftApp) { + for _ in 0..10_000 { + if !app.session.script_running() { + return; + } + script_runs::poll(app); + } + panic!("the script did not end"); +} + +const DRAW: &str = "vc.run('shape.rectangle', {x:0,y:0,width:10,height:10}); vc.run('shape.rectangle', {x:20,y:0,width:10,height:10});"; + +fn confirm(app: &mut VectorcraftApp) -> Result { + dialogs::confirm(app) +} + +#[test] +fn the_warning_comes_before_the_run_and_cancel_runs_nothing() { + let mut app = app(); + menus::run_ui_command(&mut app, "ui.runScript", &json!({"source": DRAW, "name": "draw.js"})).unwrap().unwrap(); + let d = app.ui.dialog.as_ref().unwrap(); + assert_eq!((d.kind.as_str(), d.fields["name"].as_str()), (dialogs::script_run::KIND, Some("draw.js"))); + assert!(!app.session.script_running()); + dialogs::cancel(&mut app); + assert!(app.ui.dialog.is_none()); + assert!(!app.session.script_running()); + finish(&mut app); + assert_eq!(objects(&app), 0); +} + +#[test] +fn a_run_goes_frame_by_frame_and_is_one_undo_step() { + let mut app = app(); + let dir = folder("draw"); + let path = dir.join("Dessin (été) #1.JSX"); + std::fs::write(&path, DRAW).unwrap(); + let undo = app.session.doc().unwrap().history.undo.len(); + menus::run_ui_command(&mut app, "ui.runScript", &json!({"path": path.to_string_lossy()})).unwrap().unwrap(); + assert_eq!(app.ui.dialog.as_ref().unwrap().fields["name"], "Dessin (été) #1.JSX"); + confirm(&mut app).unwrap(); + assert!(app.session.script_running()); + assert_eq!(objects(&app), 0, "nothing shows until the run commits"); + finish(&mut app); + assert_eq!(objects(&app), 2); + assert_eq!(app.session.doc().unwrap().history.undo.len(), undo + 1); + assert_eq!(app.ui.status, "Ran Dessin (été) #1.JSX"); + app.run("edit.undo", json!({})).unwrap(); + assert_eq!(objects(&app), 0); + let _ = std::fs::remove_dir_all(&dir); +} + +#[test] +fn do_not_show_again_is_remembered_and_the_script_still_runs() { + let mut app = app(); + menus::run_ui_command(&mut app, "ui.runScript", &json!({"source": DRAW})).unwrap().unwrap(); + app.ui.dialog.as_mut().unwrap().fields.insert("dontShow".into(), json!(true)); + confirm(&mut app).unwrap(); + finish(&mut app); + assert!(!app.session.prefs.show_external_script_warning); + menus::run_ui_command(&mut app, "ui.runScript", &json!({"source": DRAW})).unwrap().unwrap(); + assert!(app.ui.dialog.is_none()); + assert!(app.session.script_running()); + finish(&mut app); + assert_eq!(objects(&app), 4); +} + +#[test] +fn only_js_and_jsx_files_are_taken() { + let mut app = app(); + for name in ["a.txt", "a.jsxbin", "a"] { + let e = menus::run_ui_command(&mut app, "ui.runScript", &json!({ "path": name })).unwrap().unwrap_err(); + assert!(e.contains(".js or .jsx"), "{name}: {e}"); + } + assert!(app.ui.dialog.is_none()); +} + +#[test] +fn stop_puts_the_document_back_and_says_so() { + let mut app = app(); + app.session.prefs.show_external_script_warning = false; + let source = format!("{DRAW} while (true) {{}}"); + menus::run_ui_command(&mut app, "ui.runScript", &json!({ "source": source })).unwrap().unwrap(); + script_runs::poll(&mut app); + assert!(app.session.script_running()); + assert!(app.run("shape.rectangle", json!({"x": 0, "y": 0, "width": 1, "height": 1})).unwrap_err().contains("a script is running")); + app.run("script.stop", json!({})).unwrap(); + finish(&mut app); + assert_eq!(objects(&app), 0); + assert_eq!(app.ui.status, "The script was stopped and its changes were undone"); +} + +#[test] +fn a_script_error_goes_to_the_status_bar() { + let mut app = app(); + app.session.prefs.show_external_script_warning = false; + menus::run_ui_command(&mut app, "ui.runScript", &json!({"source": "throw new Error('nope');", "name": "x.js"})).unwrap().unwrap(); + finish(&mut app); + assert_eq!(app.ui.status, "x.js: line 1, column 1: Error: nope (thrown)"); +} + +/// An app whose script picker is the web's: picks are counted and files arrive through its inbox. +fn app_with_picker() -> (VectorcraftApp, dialogs::script_run::ScriptInbox, std::rc::Rc>) { + let mut app = app(); + let inbox = dialogs::script_run::ScriptInbox::default(); + let picks = std::rc::Rc::new(std::cell::Cell::new(0)); + let counted = picks.clone(); + app.services.script_async = Some(Box::new(move || counted.set(counted.get() + 1))); + app.services.script_inbox = Some(inbox.clone()); + (app, inbox, picks) +} + +#[test] +fn a_canceled_web_pick_does_not_take_a_dropped_script() { + let (mut app, _inbox, picks) = app_with_picker(); + menus::run_ui_command(&mut app, "ui.runScript", &json!({})).unwrap().unwrap(); + assert_eq!(picks.get(), 1); + // A pick that was canceled delivers nothing, and the next file that opens is an ordinary open. + script_runs::poll(&mut app); + let _ = crate::io::open_bytes(&mut app, "dropped.js", DRAW.as_bytes(), None); + assert!(app.ui.dialog.as_ref().is_none_or(|d| d.kind != dialogs::script_run::KIND)); + assert!(!app.session.script_running()); + assert_eq!(objects(&app), 0); +} + +#[test] +fn a_web_pick_goes_to_the_warning_and_waits_for_an_open_dialog() { + let (mut app, inbox, _picks) = app_with_picker(); + app.ui.dialog = Some(crate::state::Dialog::new(dialogs::script_run::CLOSE_KIND, json!({}))); + inbox.lock().unwrap().push(("picked.js".to_string(), Some(DRAW.as_bytes().to_vec()))); + script_runs::poll(&mut app); + assert_eq!(app.ui.dialog.as_ref().unwrap().kind, dialogs::script_run::CLOSE_KIND); + assert_eq!(inbox.lock().unwrap().len(), 1, "the file waits"); + app.ui.dialog = None; + script_runs::poll(&mut app); + let d = app.ui.dialog.as_ref().unwrap(); + assert_eq!((d.kind.as_str(), d.fields["name"].as_str()), (dialogs::script_run::KIND, Some("picked.js"))); + confirm(&mut app).unwrap(); + finish(&mut app); + assert_eq!(objects(&app), 2); +} + +#[test] +fn a_web_pick_that_is_not_text_is_reported() { + let (mut app, inbox, _picks) = app_with_picker(); + inbox.lock().unwrap().push(("bad.js".to_string(), Some(vec![0xff, 0xfe]))); + script_runs::poll(&mut app); + assert!(app.ui.dialog.is_none()); + assert_eq!(app.ui.status, "the script is not UTF-8 text"); +} + +#[test] +fn a_web_pick_too_large_to_read_is_reported() { + let (mut app, inbox, _picks) = app_with_picker(); + inbox.lock().unwrap().push(("big.js".to_string(), None)); + script_runs::poll(&mut app); + assert!(app.ui.dialog.is_none()); + assert_eq!(app.ui.status, "the script is too large to run"); +} + +/// A run that never ends, with the growth question up. +fn at_the_growth_question(app: &mut VectorcraftApp) { + app.session.prefs.show_external_script_warning = false; + let source = format!("{DRAW} while (true) {{}}"); + menus::run_ui_command(app, "ui.runScript", &json!({ "source": source })).unwrap().unwrap(); + script_runs::poll(app); + assert!(app.session.script_running()); + app.ui.dialog = Some(crate::state::Dialog::new(dialogs::script_run::GROWTH_KIND, json!({}))); +} + +#[test] +fn the_growth_questions_stop_button_stops_the_run() { + let mut app = app(); + at_the_growth_question(&mut app); + dialogs::cancel(&mut app); + assert!(app.ui.dialog.is_none()); + finish(&mut app); + assert_eq!(objects(&app), 0); + assert_eq!(app.ui.status, "The script was stopped and its changes were undone"); +} + +#[test] +fn escape_on_the_growth_question_stops_the_run() { + let mut app = app(); + at_the_growth_question(&mut app); + let key = egui::Key::Escape; + let events = vec![egui::Event::Key { key, physical_key: Some(key), pressed: true, repeat: false, modifiers: egui::Modifiers::NONE }]; + let ctx = egui::Context::default(); + let mut output = ctx.run_ui(egui::RawInput { events, ..Default::default() }, |ui| crate::shortcuts::handle(&mut app, ui.ctx())); + output.textures_delta.clear(); + assert!(app.ui.dialog.is_none()); + finish(&mut app); + assert_eq!(objects(&app), 0); + assert_eq!(app.ui.status, "The script was stopped and its changes were undone"); +} + +#[test] +fn a_stopped_run_closes_its_growth_question() { + let mut app = app(); + app.session.prefs.show_external_script_warning = false; + menus::run_ui_command(&mut app, "ui.runScript", &json!({"source": "while (true) {}"})).unwrap().unwrap(); + script_runs::poll(&mut app); + app.ui.dialog = Some(crate::state::Dialog::new(dialogs::script_run::GROWTH_KIND, json!({}))); + app.run("script.stop", json!({})).unwrap(); + finish(&mut app); + assert!(app.ui.dialog.is_none()); +} + +#[test] +fn finished_background_work_waits_for_the_run_to_end() { + let mut app = app(); + app.session.prefs.show_external_script_warning = false; + app.opening.activate.push(("no such document".to_string(), vectorcraft_engine::file_access::ScopeHandle::capture())); + menus::run_ui_command(&mut app, "ui.runScript", &json!({"source": "while (true) {}"})).unwrap().unwrap(); + app.poll_finished_work(); + assert_eq!(app.opening.activate.len(), 1); + app.run("script.stop", json!({})).unwrap(); + finish(&mut app); + app.poll_finished_work(); + assert!(app.opening.activate.is_empty()); +} + +#[test] +fn quitting_asks_to_stop_and_stop_undoes_the_run() { + let mut app = app(); + app.session.prefs.show_external_script_warning = false; + let source = format!("{DRAW} while (true) {{}}"); + menus::run_ui_command(&mut app, "ui.runScript", &json!({ "source": source })).unwrap().unwrap(); + script_runs::poll(&mut app); + assert!(app.session.script_running()); + app.ui.dialog = Some(crate::state::Dialog::new(dialogs::script_run::CLOSE_KIND, json!({}))); + confirm(&mut app).unwrap(); + assert!(!app.session.script_running()); + assert_eq!(objects(&app), 0); + assert!(app.ui.dialog.is_none()); + assert_eq!(app.ui.status, "The script was stopped and its changes were undone"); +} + +#[test] +fn a_stop_names_the_files_the_run_left_written() { + let mut app = app(); + app.session.prefs.show_external_script_warning = false; + let dir = folder("written"); + let path = dir.join("out.svg"); + let p = path.to_string_lossy().into_owned(); + let source = format!("vc.run('document.export', {{path: {p:?}, format: 'svg'}}); while (true) {{}}"); + menus::run_ui_command(&mut app, "ui.runScript", &json!({ "source": source })).unwrap().unwrap(); + script_runs::poll(&mut app); + assert!(path.exists()); + app.ui.dialog = Some(crate::state::Dialog::new(dialogs::script_run::CLOSE_KIND, json!({}))); + confirm(&mut app).unwrap(); + assert!(app.ui.status.contains(&p), "{}", app.ui.status); + let _ = std::fs::remove_dir_all(&dir); +} + +#[test] +fn a_new_app_shows_the_warning_by_default() { + assert!(Session::new().prefs.show_external_script_warning); +} diff --git a/crates/ui-egui/src/widgets.rs b/crates/ui-egui/src/widgets.rs index c70cca1736..56bac98081 100644 --- a/crates/ui-egui/src/widgets.rs +++ b/crates/ui-egui/src/widgets.rs @@ -63,6 +63,7 @@ pub use numeric::{ }; #[cfg(test)] use numeric::{decimal_point, field_number, share_of, spinner_step, step_through, step_to_multiple, within_a_millionth}; +pub(crate) use panel_chrome::{PANEL_FOOTER, panel_footer, panel_footer_bottom, panel_footer_space, panel_list_height}; pub use panel_chrome::{bottom_bar, layout_button, list_box, orientation_button, tab_bar}; pub(crate) use text::{ arm_field_focus, dialog_focus_flag, dialog_reject_commit_flag, disarm_field_focus, enter_modifiers, focus_field, own_field_shift_enter, diff --git a/crates/ui-egui/src/widgets/panel_chrome.rs b/crates/ui-egui/src/widgets/panel_chrome.rs index e07367dab4..2c84716281 100644 --- a/crates/ui-egui/src/widgets/panel_chrome.rs +++ b/crates/ui-egui/src/widgets/panel_chrome.rs @@ -1,5 +1,41 @@ use super::{Color32, CornerRadius, Pos2, Rect, Response, Sense, Stroke, StrokeKind, Tokens, Ui, Vec2, icons, pos2, theme, vec2}; +pub(crate) const PANEL_FOOTER: &str = "vectorcraft-panel-footer"; +const FOOTER_HEIGHT: f32 = 31.0; + +/// The finite body edge supplied by a sized dock, float or user-resized flyout. +/// Untouched flyouts omit it so their content can still determine their height. +pub(crate) fn panel_footer_bottom(ui: &Ui) -> Option { + ui.stack().iter().find_map(|stack| stack.tags().get_downcast::>(PANEL_FOOTER)).copied().flatten() +} + +/// Space left for a list above the footer and any intervening controls, or its unfitted fallback. +pub(crate) fn panel_list_height(ui: &Ui, fallback: f32, after: f32) -> f32 { + panel_footer_bottom(ui).map_or(fallback, |bottom| (bottom - ui.next_widget_position().y - FOOTER_HEIGHT - after).max(0.0)) +} + +/// Pad short content so a footer of `height` ends at the panel's saved bottom edge. +pub(crate) fn panel_footer_space(ui: &mut Ui, height: f32) { + if let Some(bottom) = panel_footer_bottom(ui) { + ui.add_space((bottom - ui.next_widget_position().y - height).max(0.0)); + } +} + +/// Pin a custom footer (for example the Variables panel's two rows). +pub(crate) fn panel_footer(ui: &mut Ui, height: f32, add: impl FnOnce(&mut Ui)) { + let Some(bottom) = panel_footer_bottom(ui) else { return add(ui) }; + let top = bottom - height; + if ui.next_widget_position().y > top { + ui.add_space(height); + } + let rect = Rect::from_min_size(pos2(ui.max_rect().left(), top), vec2(ui.available_width(), height)); + ui.painter().rect_filled(rect, 0.0, Tokens::get(ui.ctx()).panel); + // Own the blank parts too, so a click cannot select a scrolled row behind the footer. + let _background = ui.interact(rect, ui.scope_id().with("panel-footer-background"), Sense::CLICK); + ui.scope_builder(egui::UiBuilder::new().max_rect(rect), add); + ui.advance_cursor_after_rect(rect); +} + /// A bordered list box (Swatches tiles, Appearance rows, Artboards list). pub fn list_box(ui: &mut Ui, add: impl FnOnce(&mut Ui) -> R) -> R { let t = Tokens::get(ui.ctx()); @@ -9,6 +45,25 @@ pub fn list_box(ui: &mut Ui, add: impl FnOnce(&mut Ui) -> R) -> R { /// A bottom button bar separated from the content by a divider (panel footers). pub fn bottom_bar(ui: &mut Ui, add: impl FnOnce(&mut Ui)) { let t = Tokens::get(ui.ctx()); + if let Some(bottom) = panel_footer_bottom(ui) { + // Reserve scrollable room after long content so its final row can move above + // the pinned footer instead of remaining hidden underneath its buttons. + let top = bottom - FOOTER_HEIGHT; + if ui.next_widget_position().y > top { + ui.add_space(FOOTER_HEIGHT); + } + let footer = Rect::from_min_size(pos2(ui.max_rect().left(), top), vec2(ui.available_width(), FOOTER_HEIGHT)); + ui.painter().rect_filled(footer, 0.0, t.panel); + let _background = ui.interact(footer, ui.scope_id().with("panel-footer-background"), Sense::CLICK); + ui.painter().hline(footer.x_range(), top + 4.0, Stroke::new(1.0, t.divider)); + let row = Rect::from_min_max(pos2(footer.left(), top + 7.0), footer.max); + ui.scope_builder(egui::UiBuilder::new().max_rect(row).layout(egui::Layout::left_to_right(egui::Align::Center)), |ui| { + ui.spacing_mut().item_spacing.x = 4.0; + add(ui); + }); + ui.advance_cursor_after_rect(footer); + return; + } ui.add_space(4.0); let (r, _) = ui.allocate_exact_size(vec2(ui.available_width(), 1.0), Sense::hover()); ui.painter().rect_filled(r, 0.0, t.divider); @@ -202,3 +257,40 @@ pub(super) fn chevron_cell(ui: &mut Ui, h: f32) -> Response { dresp.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, ui.is_enabled(), tl!("Presets"))); dresp } + +#[cfg(test)] +mod footer_tests { + use super::{PANEL_FOOTER, bottom_bar, panel_footer}; + + /// Blank footer space intercepts clicks instead of selecting list rows underneath it. + #[test] + fn blank_footer_space_does_not_click_a_row_scrolled_behind_it() { + use egui::{Event, PointerButton, Rect, Sense, UiBuilder, UiStackInfo, pos2}; + for custom in [false, true] { + let ctx = egui::Context::default(); + let mut clicked = false; + let at = pos2(150.0, 190.0); + let button = |pressed| Event::PointerButton { pos: at, button: PointerButton::Primary, pressed, modifiers: Default::default() }; + for events in [vec![], vec![], vec![Event::PointerMoved(at), button(true)], vec![button(false)]] { + let input = + egui::RawInput { screen_rect: Some(Rect::from_min_max(pos2(0.0, 0.0), pos2(200.0, 200.0))), events, ..Default::default() }; + let mut output = ctx.run_ui(input, |ui| { + let info = UiStackInfo::default().with_tag_value(PANEL_FOOTER, Some(200.0_f32)); + ui.scope_builder(UiBuilder::new().ui_stack_info(info), |ui| { + clicked |= ui.allocate_rect(Rect::from_min_max(pos2(0.0, 100.0), pos2(200.0, 200.0)), Sense::click()).clicked(); + let contents = |ui: &mut egui::Ui| { + let _button = ui.button("Footer button"); + }; + if custom { + panel_footer(ui, 31.0, contents); + } else { + bottom_bar(ui, contents); + } + }); + }); + output.textures_delta.clear(); + } + assert!(!clicked, "custom={custom}: a hidden row received the footer click"); + } + } +} diff --git a/docs/dimensions.md b/docs/dimensions.md index e55e698f2b..1f1db9a492 100644 --- a/docs/dimensions.md +++ b/docs/dimensions.md @@ -4,8 +4,11 @@ The **Dimension Tool** is in the Modify section of the toolbar. Its strip offers **Angular**, **Radial** and **Tool Options…** (double-clicking the tool opens Tool Options too). - **Linear:** hover a path segment and drag outwards: releasing places the dimension. Or click two - points (anchors snap, Shift constrains to 45°), then click to place. A curved segment is measured - from end to end. With Smart Guides on, both points also snap into line with other objects' + points (anchors snap, Shift constrains to 45°), then click to place. A click within 8 pixels of + an anchor of any path, in groups and compound paths too, takes that anchor, and the dimension + stays linked to it. A press on an anchor picks it when the pointer moves less than 8 pixels + before the release; a longer drag drags out the dimension of the segment under the pointer. A + curved segment is measured from end to end. With Smart Guides on, both points also snap into line with other objects' anchors and centres, and the second onto the construction guides through the first; the guides show while hovering, before each click. - **Angular:** hover a corner where two straight segments meet and drag outwards. Or click two diff --git a/docs/file-format-parity.md b/docs/file-format-parity.md index 10dded6237..f4652f5395 100644 --- a/docs/file-format-parity.md +++ b/docs/file-format-parity.md @@ -1,6 +1,6 @@ # File format parity -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-09 · **Change:** minor (PDF import: DeviceN images of one ink or of process plates keep their inks, #6348; `.ai` import: images in a spot ink's Separation space keep their ink, #6350; PDF import: Separation images keep their ink, #6314; PDF editable import preserves authored ActualText once, including empty/nested spans and authored ordering (#6165); cross-line/style layout remains approximate; scores and estimates unchanged; PDF marked-text export (#6309): compatible glyphs stay on one layout line with per-glyph offsets; scores and estimates unchanged; PDF import: image masks open colorized by the color they are painted in, #6313; EPS and `.ai` editing data: a ligature the page names by a private-use glyph matches its text object; EPS import: CIDFonts only named, over a Unicode CMap, set as live type; EPS import: CMap mappings to base-font codes and glyph names; EPS import: CID-keyed fonts in FontSets (CFF) draw their glyphs; EPS import: `kshow` procedures kern live type; EPS import: embedded Type 1 fonts' glyphs and widths; EPS import: CID-keyed fonts draw their glyphs; EPS import: Type 42 fonts' characters and widths from the font they carry, show operators' spacing kept as tracking; EPS import: an image decoder's own buffers stop counting against the memory budget once it is decoded; EPS import: sampled functions interpolate between their samples; `.ai` and EPS type from the text document keeps its tab stops; it keeps auto leading and hyphenation options, and may show more of the file's last lines in an area frame; `.ai` and EPS import: Art brushes in the older form of their objects come into the Brushes panel; EPS import: gradients drawn as abutting strips come in as one gradient, without seams; EPS import: composite fonts draw their Type 42 glyphs; SVG import: filter and mask regions clip, #5876, #5875; SVG import: Gaussian blurs keep `color-interpolation-filters`, #5877; PDF and `.ai` export: objects' URLs as links, #5785; SVG import: `color-interpolation="linearRGB"` gradients, #5878; `.ai` import: paths with a Calligraphic brush open brushed, #372) · **Target:** Adobe Illustrator 2026 (30.x) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-10 · **Change:** minor (`.ai` and EPS import: a note for type in an envelope, #3179; `.ai` and EPS import: the live envelope and warped type check sees white art; PDF import: DeviceN images of one ink or of process plates keep their inks, #6348; `.ai` import: images in a spot ink's Separation space keep their ink, #6350; PDF import: Separation images keep their ink, #6314; PDF editable import preserves authored ActualText once, including empty/nested spans and authored ordering (#6165); cross-line/style layout remains approximate; scores and estimates unchanged; PDF marked-text export (#6309): compatible glyphs stay on one layout line with per-glyph offsets; scores and estimates unchanged; PDF import: image masks open colorized by the color they are painted in, #6313; EPS and `.ai` editing data: a ligature the page names by a private-use glyph matches its text object; EPS import: CIDFonts only named, over a Unicode CMap, set as live type; EPS import: CMap mappings to base-font codes and glyph names; EPS import: CID-keyed fonts in FontSets (CFF) draw their glyphs; EPS import: `kshow` procedures kern live type; EPS import: embedded Type 1 fonts' glyphs and widths; EPS import: CID-keyed fonts draw their glyphs; EPS import: Type 42 fonts' characters and widths from the font they carry, show operators' spacing kept as tracking; EPS import: an image decoder's own buffers stop counting against the memory budget once it is decoded; EPS import: sampled functions interpolate between their samples; `.ai` and EPS type from the text document keeps its tab stops; it keeps auto leading and hyphenation options, and may show more of the file's last lines in an area frame; `.ai` and EPS import: Art brushes in the older form of their objects come into the Brushes panel; EPS import: gradients drawn as abutting strips come in as one gradient, without seams; EPS import: composite fonts draw their Type 42 glyphs; SVG import: filter and mask regions clip, #5876, #5875; SVG import: Gaussian blurs keep `color-interpolation-filters`, #5877; PDF and `.ai` export: objects' URLs as links, #5785; SVG import: `color-interpolation="linearRGB"` gradients, #5878; `.ai` import: paths with a Calligraphic brush open brushed, #372) · **Target:** Adobe Illustrator 2026 (30.x) Every format Illustrator opens, places, saves or exports, against VectorCraft's format table (`FORMATS`, `OPEN_EXTS`, `PLACE_EXTS` in `crates/engine/src/cmd/fileio/formats.rs`). Illustrator's list comes from its public @@ -286,7 +286,7 @@ Names in the editing data that aren't UTF-8 (layers, objects, artboards, colors, | PDF | open, place, save | yes (authored ActualText in editable import, #6165; layers, masks, editable text, security, overprint, File Info from the XMP packet and the document information dictionary; Crop To › Trim takes the bleed box as the document's bleed) | yes (presets, PDF/X-1a/3/4, layers, marks and bleed, ICC, fast web view, 1.3+; objects' URLs as link annotations, not in PDF/X) | fuzzed import; shared guarded writer and windowed reader ([pdf-backend.md](pdf-backend.md)), metadata, incomplete-content and dependency-source regressions; PDF text opens where the file draws it, glyph by glyph (#722: kerning or none, spacing per character, text rise as baseline shift, vertical writing, justified text boxes); alpha soft masks drawn as images import with the mask (#1551); a clip only counts as covering the page when its shape does (#1542); a PDF another app copied pastes as editable vector art (#1499); letter-spaced type on a path keeps its length and its glyph-by-glyph stroke comes in as one text object (#1586, #1585); a crafted name tree with shared nodes no longer takes exponential time on open (#1781); fonts named with hyphens (`Noto-Sans-Bold`) or with a composite font's CMap (`Name-Identity-H`) find the installed family; invisible text (rendering mode 3: a scanned page's recognized text) opens as type with no fill or stroke and saves back as invisible, searchable text (#2675); PDF/X-1a and X-3 flattening in a CMYK document keeps CMYK inks where it rasterizes (#2160); an image mask (`/ImageMask true`) painted in a solid color opens as a grayscale image colorized by that color, a spot color keeping its swatch and tint, so Fill and Recolor Artwork reach it, and the same mask painted again in another color keeps that color (#6313); an image in a Separation space opens as a grayscale image of its tints colorized by its ink at 100 % (a spot swatch, a process plate or Registration), its soft mask as its opacity mask (#6314); a DeviceN image of one colorant opens the same way, and one of process plates only (the ink `None` may be among them) opens in CMYK with each colorant's tint in its plate (#6348) PDF export keeps harakat and zero-advance Noto Arabic dot glyphs in one compatible batch per layout line, with per-glyph vertical offsets (#6309). `crates/pdf/src/tests/realtext.rs` (`mark_text_*`) checks decoded cluster mappings, mixed Arabic/Latin/digits, contour placement against outline export, vertical columns, differing path rotations and PDF/X-1a/3/4. Editable-text import preserves authored ActualText separately (#6165), with cross-line/style layout limits; separately styled or differently rotated clusters and external viewer search/copy remain outside this export-only evidence. | | EPS | open, place, save | yes (own PostScript L3 interpreter, Illustrator EPS editing data structure) | yes (L2/L3, TIFF previews) | CIDFonts the file doesn't carry not drawn, but for those over a predefined Unicode CMap (`UniJIS-UCS2-H`), set as type in the font of the CIDFont's name; name-keyed fonts in a FontSet set as type by name; #505; images encoded with `CCITTFaxDecode` (ITU-T T.4 Group 3 and T.6 Group 4, with `K`, `Columns`, `Rows`, `EndOfBlock`, `EndOfLine`, `EncodedByteAlign` and `BlackIs1`) draw, and damaged data keeps the rows decoded before its first damaged row; Type 42 (TrueType) fonts set type at its size (#1553); an embedded Type 1 font's encrypted part is read for its glyphs, which space its type, outline it and draw glyphs without a character, in plain and composite fonts; a Type 42 font that carries its TrueType font gives each code its character by its glyph name or, for names that say nothing (`/g12`), by the glyph's entry in the font's own character map, spaces its type by its own widths and draws glyphs that stand for no character from its outlines; the show operators' spacing along the baseline (`ashow`, `widthshow`, `xshow`, `yshow`, `xyshow`, and the moves of `kshow`'s procedure, run between each two characters) is kept on live type as tracking, so type in a font that isn't installed keeps the file's line lengths (spacing that moves characters off the baseline, as `yshow`, `xyshow` or a `kshow` procedure can, places each character as its own text object); composite (Type 0) fonts with the 8/8 mapping, as PDF-to-PostScript converters write two-byte fonts, draw a Type 42 descendant's glyphs from the TrueType outlines it carries and an embedded Type 1 descendant's from its charstrings, and set other descendants' characters as type at the composite font's size (other mappings are still set as type in the font of their name); CID-keyed fonts (`composefont`, `FMapType` 9 over a CMap built with the CIDInit operators or `Identity-H`/`Identity-V`; `bfchar` and `bfrange` mappings give a base-font descendant its codes or glyph names) draw the glyphs of the Type 0 CIDFonts (Type 1 charstrings in their `StartData` binary data or `GlyphDirectory`) and Type 2 CIDFonts (TrueType glyphs through `CIDMap`) they carry, and the CID-keyed fonts of a FontSet's Compact Font Format data (Type 2 charstrings); a clip only counts as covering the page when its shape does (#1542); an EPS another app copied pastes as editable vector art (`clipboard.importEps`, #1499); a stitched shading keeps its hard colour changes on import (#1654); sampled functions (type 0) interpolate between their samples, multilinearly or by cubics with `Order 3`, and a sampled axial or radial gradient has a stop at each sample; a gradient the page paints as a row of abutting one-colour strips (as Level 2 writers draw smooth shades) imports as one linear gradient, without the seams the strips leave when each is drawn alone; CMYK images, CMYK JPEGs included, keep their ink amounts on import, as from PDF, and the pixels a `MaskColor` or `ImageType 3` mask hides become a grayscale opacity mask; ruzstd 0.9.1 for compressed editing data (#1807, RUSTSEC-2026-0344) | | PostScript `.ps` | open, place | yes (the EPS reader reads its first page; `.epsf` files open and place as EPS) | via Print to PostScript | `tests_epsimport.rs` | -| SVG / SVGZ | open, place, save | yes | yes (SVG Options, Preserve Editing, symbols, filters, rich text) | strongest format; tests in `crates/svg/tests`; text on a path follows basic shapes as their SVG 2 equivalent paths (#1527); CSS transforms and the `font` shorthand (#1565), percentage lengths in symbols (#1596), Inkscape flowed text as area type (#1568) and Inkscape pages as artboards (#1601) import; an unsupported filter is named in its warning (#1598); an artboard exported on its own (Export As with Use Artboards, Export for Screens, Asset Export) has the artboard's name as ``, Save the document's (#3544); attributes in other applications' XML namespaces (`plotter:pen="2"`) kept on their objects from import to export, as `data-*` attributes are (`crates/svg/tests/it/foreign_attributes.rs`); simple shapes export as `<rect>`, `<circle>`, `<ellipse>`, `<line>`, `<polygon>` and `<polyline>` where they draw the same as the path (#4652, `crates/svg/tests/it/basic_shapes.rs`) | +| SVG / SVGZ | open, place, save | yes | yes (SVG Options, Preserve Editing, symbols, filters, rich text) | strongest format; tests in `crates/svg/tests`; text on a path follows basic shapes as their SVG 2 equivalent paths (#1527); CSS transforms and the `font` shorthand (#1565), percentage lengths in symbols (#1596), Inkscape flowed text as area type (#1568) and Inkscape pages as artboards (#1601) import; an unsupported filter is named in its warning (#1598); an artboard exported on its own (Export As with Use Artboards, Export for Screens, Asset Export) has the artboard's name as `<title>`, Save the document's (#3544); attributes in other applications' XML namespaces (`plotter:pen="2"`) kept on their objects from import to export, as `data-*` attributes are (`crates/svg/tests/it/foreign_attributes.rs`); simple shapes export as `<rect>`, `<circle>`, `<ellipse>`, `<line>`, `<polygon>` and `<polyline>` where they draw the same as the path (#4652, `crates/svg/tests/it/basic_shapes.rs`); the regions of exported masks and filters (opacity masks, inverted masks, knockout groups) cover the art they apply to, and over type keep a region that covers any artwork (#6401, `crates/svg/tests/it/blend_export.rs`) | | DXF | open, export | yes | yes (R12–2018) | R13–2018 closed SPLINE flags and control-point closure on import verified (#1299); circular cubic paths export as native CIRCLE/ARC where stroke semantics permit; R12 weighted strokes remain POLYLINE while non-circular curves keep the existing fallback (`crates/cad/src/tests.rs`); [Autodesk group 70](https://help.autodesk.com/cloudhelp/2024/ENU/AutoCAD-DXF/files/GUID-E1F884F8-AA90-4864-A215-3182D47A9C74.htm). DXF 2000–2018 LAYOUT objects write the paper image origin as 148/149 (was a stray 158), the shade plot codes (2004+) and the model type flag, and the plot style placeholder carries no subclass marker (#3085; structure test `r2000_and_later_files_have_the_structure_cad_apps_require`, checked with ezdxf's audit; not yet confirmed in Autodesk Fusion). CNC preset and VCarve QA remain open | | DWG | open, export | no | no | no open spec; DXF instead | | EMF / WMF | open, export | yes | yes | an oversized embedded PNG or JPEG is refused from its header, before any pixels are decoded (#1776) | @@ -311,6 +311,15 @@ Names in the editing data that aren't UTF-8 (layers, objects, artboards, colors, | Affinity `.af`, `.afdesign`, `.afpub` | no | yes (beyond Illustrator) | no (#665) | 51 pinned files, [affinity-validation.md](affinity-validation.md) | | Clipboard: PDF, SVG, PNG, EMF, text | yes | yes | yes | copied files paste as art; cells copied from a spreadsheet (tab-separated text) paste as a table of point type over gridlines, at most 1000 rows, 256 columns and 20,000 cells (#5296) | +## PDF form gradients + +PDF export's linear and radial gradients stay aligned inside transparency groups, opacity masks, +PDF layers and overprinting art. The original synthetic tests in +`crates/pdf/tests/gradient_forms.rs` check the output with macOS Quartz and an import/render +round trip. The three Quartz checks fail on main `65adb7b21` and pass with the form-space fix; +translated layer bounds also have a regression for the current writer's layer-box repair. +Stop opacity on translated artboards remains outside this regression coverage. + ## PDF editable imports - [x] Explicit `/ActualText` replaces covered glyph text once, including empty strings and nested spans (outer owner wins), while later glyphs retain pen geometry. Synthetic regressions in `crates/pdf/src/tests/actual_text.rs`; no added fonts/assets. UTF-16BE, BOM UTF-8 and PDFDocEncoding reuse the reader's text-string decoder. @@ -327,6 +336,8 @@ Names in the editing data that aren't UTF-8 (layers, objects, artboards, colors, | Date | Change | Summary | |---|---|---| +| 2026-11-10 | minor | `.ai` and EPS import: an envelope of type, which keeps its drawn art with its type hidden, now says so in the import notes ("type in an envelope comes in as the envelope's drawn art, not as editable type"); nothing said it before, while the other envelopes that keep their drawn art have a note. The type is still not editable in the envelope (part of #3179). Test `tests_native::envelope_options_keep_the_source_text_hidden_under_its_outlined_appearance` | +| 2026-11-10 | minor | `.ai` and EPS import: the check that keeps a live envelope or warped type only where it draws as the art saved with it renders each on its own, over nothing, and compared the pixels seen on white, where white art looks like nothing. White contents that drew somewhere else passed it and opened live in the wrong place (white warped type off its banner, in users' files). Pixels now also differ when they look different seen on black, so such art keeps its saved art, as colored art does. Tests `import::ai::tests::a_white_envelope_that_doesnt_come_out_as_drawn_keeps_its_drawn_art`, `white_warped_type_that_draws_elsewhere_comes_in_as_its_look` | | 2026-11-10 | minor | PDF import: an image in a DeviceN space of one colorant opens as a Separation image does (#6314): a grayscale image of its tints colorized by its ink. One of two or more colorants that are all process plates (Cyan, Magenta, Yellow, Black, and the ink `None`) opens as a CMYK image, each colorant's tint in its plate and its Decode array applied (8 or 16 bits a sample; one that can't be read, such as a JPEG, opens in RGB with the CMYK images' warning). Both used to open as RGB images, losing their inks. A DeviceN image that mixes a spot ink with other colorants, such as a duotone, still opens as RGB: an image holds one ink or the process plates, not both (#6348). Tests `colorize::a_devicen_image_of_one_ink_opens_colorized_by_it`, `colorize::a_devicen_image_of_process_plates_opens_in_cmyk`, `colorize::a_duotone_devicen_image_still_opens_as_rgb` | | 2026-11-09 | minor | `.ai` import: an image whose color space `XC` sets to one ink (`n [c m y k /DeviceCMYK (name) /Separation] XC`, or an RGB alternate) opened as a gray RGB image: its samples, the ink's tints (255 at 100 %), were read as gray levels, so the tints drew inverted and the ink was lost. It now opens as a grayscale image of the tints, black at 100 %, colorized by the ink at 100 %: a spot swatch, a process plate's CMYK color (no swatch of its name), or Registration; the ink's color counts toward the document's color mode as a fill's does. Its alpha channel becomes its opacity mask, a reduced large image's too: a colorized image reduced to fit the limits (an image mask included) now keeps its alpha as an opacity mask rather than in its pixels, as at its full size. 8-bit and 1-bit samples, binary or in hex comment lines. A device space (`/DeviceGray XC` after a linked image's file name) and the ink `None` change nothing, as before; linked images (`XF`) keep their placeholder. Tests `import::ai::tests::separation_images_are_colorized_with_their_ink`, `separation_images_of_process_plates_and_registration`, `a_separation_image_with_hex_comment_lines_keeps_its_ink`, `a_reduced_separation_image_keeps_its_ink_and_its_alpha_as_a_mask` (#6350) | | 2026-11-09 | minor | PDF import: an image in a Separation color space (one ink, ISO 32000-1 §8.6.6.4) opens as a grayscale image of its tints (white where it lays no ink, black at 100 %, its Decode array applied; 1, 2, 4, 8 and 16 bits a sample, or one gray channel from its JPEG, CCITT, JBIG2 or JPEG 2000 decoder) colorized by its ink at 100 %: a spot ink's swatch, a process plate's CMYK color, or Registration. It used to open as an RGB image, losing the ink, and Fill and Recolor Artwork didn't reach its color. Its soft mask or mask becomes its opacity mask, as a CMYK image's does. The ink is found by the image's color space (kind, colorant name and tint transform), once per image. As with any colorized image, where it lays no ink the art under it shows, where the RGB image was opaque white. The ink `None`, which paints nothing, an ink whose color can't be told, an image inside an alpha soft mask, inline images and DeviceN images open as before; samples that can't be read (data cut short, a decoder's output of another layout) open in RGB with a warning, and the ink gets no swatch. Tests `colorize::a_separation_image_opens_colorized_by_its_ink`, `colorize::a_separation_image_reads_its_samples_and_decode_array`, `colorize::a_separation_image_of_a_process_plate_or_of_no_ink`, `colorize::a_separation_image_keeps_its_soft_mask`, `colorize::a_separation_image_drawn_twice_is_colorized_twice`, `colorize::a_separation_jpeg_opens_colorized_by_its_ink`, `colorize::a_separation_image_that_cant_be_read_stays_rgb` (#6314) | diff --git a/docs/gaps.md b/docs/gaps.md index cd3a77db6f..f0a231a340 100644 --- a/docs/gaps.md +++ b/docs/gaps.md @@ -1,14 +1,17 @@ # Gaps -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-10 · **Change:** minor (right-click on a word Auto Spell Check underlined: its suggestions, Ignore All and Add to Dictionary, #4936; previously minor: G2: Effect Gallery thumbnails and in-dialog preview; estimate 1–2 h → 0; Auto Spell Check: `edit.autoSpellCheck` underlines the unknown words, #4936; previously minor: PDF editable import preserves authored ActualText once, including empty/nested spans and authored ordering (#6165); cross-line/style layout remains approximate; scores and estimates unchanged; PDF marked-text export (#6309): compatible glyphs stay on one layout line with per-glyph offsets; scores and estimates unchanged; G5: built-in UI Frames symbol library with default 9-slice; estimate 11–21 h; previously minor: G5: dynamic symbol part on-canvas takes opacity, blend, gradient and pattern; docs Overlap/auto-corners sync; estimate 12–22 h; previously minor: interim macOS cursor delivery, #2292; native validation pending; scores and estimates unchanged; previously minor: Control bar › Snapping includes the existing Snap to Glyph and Alignment Guides toggles (#6164); scores and estimates unchanged; previously minor: G5 docs: Art brush Overlap, Pattern brush auto corners and Global Edit Shift-click leave-out moved from Missing to Done (code already shipped); previously minor: custom dictionary and Ignore All: `text.spelling.addWord`, `removeWord`, `changeWord`, `dictionary` and `ignoreAll`, #4936; previously minor: EPS import: embedded fonts (composite, Type 42, CID-keyed, Type 1, CFF FontSet) draw their glyphs; spell check engine: `text.spelling.check` and `text.spelling.suggest` on craft-proof, #4936; previously minor: floating tab groups collapse into the side icon rail and opened rail panels fold back into it, #5925 in part; G9: EPS gradients drawn as abutting strips import as one gradient, without seams; Tools stays beside the canvas with left-side panels; new gradients follow document color mode; Selection QoL: marquee modes and visible feedback, #5313; #3380 deletion-only review follow-up: independent survivors keep gradient placement, owned subpaths avoid discarded copies, and contracts/status/evidence are clarified; endpoint highlighting remains open; scores and estimates unchanged; Indian-language hyphenation review and license allowlist, #4947; opening a slow file shows a progress window, part of #5930; Hindi catalog and contributor loanword preferences; agent wording pass complete; wider native proofreading welcome; an image zoomed in on is separated, colorized or proofed only where it shows (#4155); scores and estimates unchanged; a document's first frame renders on the render worker, so opening a heavy file no longer freezes the window; scores and estimates unchanged; large images in CMYK documents are shrunk before they are separated into ink planes (#4155); scores and estimates unchanged; `.ai` paths with a Calligraphic brush open brushed, with the 6D Art Pen's channels, and Windows reads the pen's tilt and barrel rotation, #372; scores and estimates unchanged; Compound Shapes add-on, beyond Illustrator; scores and estimates unchanged; Contour add-on, beyond Illustrator; scores and estimates unchanged; a slow first frame is waited for instead of restarting without the graphics adapter, and the menu bar no longer waits for the installed fonts' scan; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-10 · **Change:** minor (G5: built-in Game HUD graphic style library; estimate 10–20 → 9–19 h; previously minor: G5: built-in Map Markers symbol library; estimate 11–21 → 10–20 h; previously minor: right-click on type: Spelling › Auto Spell Check, with its check mark, #4936; previously minor: right-click on a word Auto Spell Check underlined: its suggestions, Ignore All and Add to Dictionary, #4936; previously minor: G2: Effect Gallery thumbnails and in-dialog preview; estimate 1–2 h → 0; Auto Spell Check: `edit.autoSpellCheck` underlines the unknown words, #4936; previously minor: PDF editable import preserves authored ActualText once, including empty/nested spans and authored ordering (#6165); cross-line/style layout remains approximate; scores and estimates unchanged; PDF marked-text export (#6309): compatible glyphs stay on one layout line with per-glyph offsets; scores and estimates unchanged; G5: built-in UI Frames symbol library with default 9-slice; estimate 11–21 h; previously minor: G5: dynamic symbol part on-canvas takes opacity, blend, gradient and pattern; docs Overlap/auto-corners sync; estimate 12–22 h; previously minor: interim macOS cursor delivery, #2292; native validation pending; scores and estimates unchanged; previously minor: Control bar › Snapping includes the existing Snap to Glyph and Alignment Guides toggles (#6164); scores and estimates unchanged; previously minor: G5 docs: Art brush Overlap, Pattern brush auto corners and Global Edit Shift-click leave-out moved from Missing to Done (code already shipped); previously minor: custom dictionary and Ignore All: `text.spelling.addWord`, `removeWord`, `changeWord`, `dictionary` and `ignoreAll`, #4936; previously minor: EPS import: embedded fonts (composite, Type 42, CID-keyed, Type 1, CFF FontSet) draw their glyphs; spell check engine: `text.spelling.check` and `text.spelling.suggest` on craft-proof, #4936; previously minor: floating tab groups collapse into the side icon rail and opened rail panels fold back into it, #5925 in part; G9: EPS gradients drawn as abutting strips import as one gradient, without seams; Tools stays beside the canvas with left-side panels; new gradients follow document color mode; Selection QoL: marquee modes and visible feedback, #5313; #3380 deletion-only review follow-up: independent survivors keep gradient placement, owned subpaths avoid discarded copies, and contracts/status/evidence are clarified; endpoint highlighting remains open; scores and estimates unchanged; Indian-language hyphenation review and license allowlist, #4947; opening a slow file shows a progress window, part of #5930; Hindi catalog and contributor loanword preferences; agent wording pass complete; wider native proofreading welcome; an image zoomed in on is separated, colorized or proofed only where it shows (#4155); scores and estimates unchanged; a document's first frame renders on the render worker, so opening a heavy file no longer freezes the window; scores and estimates unchanged; large images in CMYK documents are shrunk before they are separated into ink planes (#4155); scores and estimates unchanged; `.ai` paths with a Calligraphic brush open brushed, with the 6D Art Pen's channels, and Windows reads the pen's tilt and barrel rotation, #372; scores and estimates unchanged; Compound Shapes add-on, beyond Illustrator; scores and estimates unchanged; Contour add-on, beyond Illustrator; scores and estimates unchanged; a slow first frame is waited for instead of restarting without the graphics adapter, and the menu bar no longer waits for the installed fonts' scan; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x) + +> **Flyout update:** 2026-11-06 — resizable icon-strip flyouts and bottom-aligned panel footers (#5713); scores and estimates unchanged. ## Feature submission evidence **Feature evidence last updated:** 2026-11-02. -| 2026-11-10 | minor | G4 type: a right-click on a word Auto Spell Check underlined lists its suggestions, Ignore All and Add to Dictionary, #4936; the Check Spelling and Edit Custom Dictionary dialogs remain; scores and estimates unchanged. | | 2026-11-06 | minor | Opening a file that takes longer than 0.4 s shows a progress window: the file name, a moving bar (reading reports no steps), how many more files wait, Cancel (Esc; the file doesn't open) and Continue in Background (`file.cancelOpen`, `file.openInBackground`); it never opens over another dialog or progress window (part of #5930); scores and estimates unchanged | Raster rendering fits and preflattens curved stroke outlines more tightly only below four times the raster tolerance, retaining thin-band coverage without changing stroke weight or vector export geometry. Current cached character/object outlines, cropped long strokes, gradient clips and effect rasters share the helper; cropped-region reuse and guarded flattening remain. The unchanged `fractional_curved_strokes_retain_coverage_between_notches` regression covers fractional weights, rotation, phase, opacity and f32-rounded endpoints. This is a quality/cost tradeoff, not a speed claim. Scores and estimates unchanged. +Icon-strip flyouts resize from the canvas-side edge and bottom, keeping the icon-column edge anchored (#5713). Independent group heights and flyout widths persist in workspaces; saved heights override content fitting while untouched heights still fit content. Shared panel button bars and the Glyphs font row stay at the bottom after enlargement; the Artboards list grows into the extra space. Regressions: `panel_docking::tests::glyphs_and_artboards_flyouts_keep_user_sizes` and `expanded_panel_footers_stay_at_the_bottom_with_short_and_long_lists`. Scores and estimates unchanged. + **PR #3273 revision — 2026-11-04:** Thin curved stroke coverage ported to the current raster-only cache, cropped-long-stroke and effect paths with guarded flattening; vector export geometry unchanged. Scores and estimates unchanged. Group Selection keeps an already selected component selected during a drag; a completed click still adds its next enclosing group. The current Direct Selection click/release machinery is shared, preserving compound-member picks, Shift deselection, isolation and masked-art dragging. Outline Stroke continues to preserve all original fills, including open contours; the change does not remove fills. Regressions: `group_selection_distinguishes_selected_leaf_drags_from_clicks` and `outline_fill_and_stroke_move_independently_with_group_selection` cover tool events, independent component movement and Undo/Redo. Scores and estimates unchanged. @@ -52,6 +55,7 @@ Artboard Options forwards the active Artboard tool's Scale Artwork with Artboard | 2026-11-05 | minor | G15: Selection skips building corner and pie widgets when the pointer is well outside a large selection; empty-canvas hover with 20,000 selected paths took 28.72 ms before and 16.41 ms after in local median runs. Other cursor targets remain active; estimate unchanged. | | 2026-11-05 | minor | G15: Direct Selection reuses one document hit result when choosing the cursor over a path; after the path hit-test improvement, a 200,000-anchor path's segment cursor took 3.72 ms before and 2.66 ms after in local median runs. Cursor behavior is unchanged; estimate unchanged. | | 2026-11-05 | minor | G15: large-selection transforms reuse object locations found during command validation; a 20,000-object nudge took 58.07 ms before and 51.26 ms after in paired median runs. Estimate unchanged. | +| 2026-11-06 | minor | Icon-strip flyouts resize on their free edges and retain sizes with workspaces (#5713); saved heights beat auto-fit; panel footers stay at the bottom after enlargement. Scores and estimates unchanged. | | 2026-11-05 | minor | G9, G14: `.ai` paths with a Calligraphic brush open brushed (the brush on the stroke, at its weight) where the object's settings are the brush's own, and the brush's Tilt, Bearing and Rotation codes come in as those channels; Windows reads the pen's tilt and barrel rotation from Windows Ink (#372). Checked against a user's file of 6D Art Pen strokes, used locally; not tried with a pen. Scores and estimates unchanged. | | 2026-11-04 | minor | Contour add-on (beyond Illustrator): drag away from a selected shape's edge to grow a live copy of it, or toward the inside to shrink it; the copy carries a live Offset Path effect, so it stays editable until Bake (Expand Appearance), a second drag changes the same Contour instead of nesting one, and a floating bar sets the distance and the Sharp, Round or Square corners. `addon.contour.set` is the command behind it. It is a built-in add-on: Object › Plug-ins › Contour, and its own heading in All Tools, with no default shortcut or toolbar slot. A VectorCraft design built on Offset Path; no other application was inspected. Scores and estimates unchanged. | | 2026-11-04 | minor | Contour tool (beyond Illustrator): drag away from a selected shape's edge to grow a live copy of it, or toward the inside to shrink it; the copy carries a live Offset Path effect, so it stays editable until Bake (Expand Appearance), a second drag changes the same Contour instead of nesting one, and a floating bar sets the distance and the Sharp, Round or Square corners. `object.contour` is the command behind it. A VectorCraft design built on Offset Path; no other application was inspected. Scores and estimates unchanged. | @@ -98,7 +102,7 @@ stage ([ROADMAP.md](../ROADMAP.md)). | 8 | [G2 Photoshop-style raster effects and the Effect Gallery](#g2-photoshop-style-raster-effects-and-the-effect-gallery) | 0 | no | [effects-parity.md](effects-parity.md) | | 9 | [G13 Illustrator 2026 (30.x) additions](#g13-illustrator-2026-30x-additions) | 13–23 | no | [target-app-parity.md](target-app-parity.md) | | 10 | [G14 Pen hardware beyond Windows pressure](#g14-pen-hardware-beyond-windows-pressure) | 4–10 | Wayland pressure | [hardware-parity.md](hardware-parity.md) | -| 11 | [G5 Brushes, symbols and libraries](#g5-brushes-symbols-and-libraries) | 11–21 | no | [target-app-parity.md](target-app-parity.md) | +| 11 | [G5 Brushes, symbols and libraries](#g5-brushes-symbols-and-libraries) | 9–19 | no | [target-app-parity.md](target-app-parity.md) | | 12 | [G3 3D and Materials](#g3-3d-and-materials) | 25–45 | no | [effects-parity.md](effects-parity.md) | | 13 | [G7 Views and windows](#g7-views-and-windows) | 15–25 | no | [ui-parity.md](ui-parity.md) | | 14 | [G6 Automation and scripting](#g6-automation-and-scripting) | 4–8 | no | [target-app-parity.md](target-app-parity.md) | @@ -450,7 +454,7 @@ macOS cursor delivery (#2292) is narrowed to a native host adapter using the exi - **Missing:** CJK vertical composition (mojikumi sets and dialog, kinsoku settings #633, manual tate-chu-yoko), Middle Eastern features beyond bidi, digit types, Character Direction and Kashidas (Middle Eastern composers, a split caret), spell check (its engine is done, #4936: `text.spelling.check` and - `text.spelling.suggest` on craft-proof; the custom dictionary and Ignore All commands; Auto Spell Check, `edit.autoSpellCheck`, with a right-click on an underlined word offering its suggestions, Ignore All and Add to Dictionary; the Check Spelling and Edit Custom Dictionary dialogs remain), + `text.spelling.suggest` on craft-proof; the custom dictionary and Ignore All commands; Auto Spell Check, `edit.autoSpellCheck`, with a right-click on an underlined word offering its suggestions, Ignore All and Add to Dictionary, and Spelling › Auto Spell Check in the context menu of type; the Check Spelling and Edit Custom Dictionary dialogs remain), Touch Type, Retype, 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. @@ -629,8 +633,9 @@ macOS cursor delivery (#2292) is narrowed to a native host adapter using the exi symbol static drops them; stored in the native format. Color eyedropper for scatter, art and pattern brushes (Hue Shift colorization; samples canvas art); symbol libraries ([public source](https://helpx.adobe.com/illustrator/desktop/manage-objects/traces-mockups-symbols/create-or-import-symbol-libraries.html)): Window › Symbol Libraries and the Symbols panel's Symbol - Libraries Menu open each library in a library panel of its own (two original libraries generated in code, - Basic Shapes and UI Frames with default 9-slice guides on Panel, Button and Bar; User Defined; Other + Libraries Menu open each library in a library panel of its own (three original libraries generated in code, + Basic Shapes, UI Frames with default 9-slice guides on Panel, Button and Bar, and Map Markers with Pin, + Flag, Crosshair and Checkpoint; User Defined; Other Library… reads the symbols of any document VectorCraft opens); a click adds a symbol to the document's Symbols with its Symbol Options and the resources it uses, as one undo step, and dragging one onto the canvas also places it; Save Symbols / Save Symbol Library writes the @@ -652,12 +657,15 @@ macOS cursor delivery (#2292) is narrowed to a native host adapter using the exi is on, a Shift-click on a highlighted match leaves it out (`select.globalEditExclude`, #3521 evidence); Direct Selection of a path, compound path or type inside a dynamic instance also takes opacity and blend (`transparency.set`) and a gradient or pattern fill or stroke (`paint.setFill` / `paint.setStroke`, - Eyedropper), for that instance only. -- **Missing:** more built-in brush and graphic-style libraries (and further symbol libraries beyond Basic - Shapes and UI Frames; original, generated in code, never Adobe's); dynamic symbols' `.ai` read and write; + Eyedropper), for that instance only; + graphic style libraries (Window › Graphic Style Libraries; seven original libraries generated in code, including + Game HUD with Health Fill, Mana Glow, Damage Flash, Quest Outline, Coin Shine and Boss Alert; User Defined; Other + Library…; `graphicStyle.libraries`, `graphicStyle.addFromLibrary`). +- **Missing:** more built-in brush libraries (and further graphic-style libraries beyond the seven shipped, and further symbol libraries beyond Basic + Shapes, UI Frames and Map Markers; original, generated in code, never Adobe's); dynamic symbols' `.ai` read and write; Global Edit of groups holding type or images, rotated copies as matches and highlighting matches before the start; 9-slice guides outside the symbol's art (a dragged guide stops at the art's edge). -- **Estimate:** 11–21 h. +- **Estimate:** 9–19 h. ## G3 3D and Materials @@ -691,8 +699,9 @@ macOS cursor delivery (#2292) is narrowed to a native host adapter using the exi ## G6 Automation and scripting -- **Missing:** a scripting surface over the command registry (Illustrator: JavaScript, File › Scripts; - #1183 is open). Actions, Batch, Variables (text, visibility, image and graph), data set CSV import and +- **Missing:** the document object model for scripts, a script console, the Scripts folder and script + directives (#1183 is open). File › Scripts › Other Script… and `script.run` run JavaScript files over the + command registry. Actions, Batch, Variables (text, visibility, image and graph), data set CSV import and export, and full agent control over MCP are done. - **Estimate:** 4–8 h. - **Done (2026-10-16):** the MCP server hears the client during a long call: `notifications/cancelled` stops a queued or running export (PDF pages, flattening, baking, drawing, artboards) without writing anything or changing the document, `ping` and the list methods answer at once, any other request that would wait behind a call running for two seconds or more is refused as busy (`-32003`, naming the call), and `_meta.progressToken` gets page progress (#2165, #2171, #2172). Reading the document during an export is not served (refused as busy); estimate unchanged. @@ -854,6 +863,10 @@ trap, and the defaults (0.25 pt, 100%, 40%) are VectorCraft's own, the pages giv | Date | Change | Summary | |---|---|---| +| 2026-11-10 | minor | G5: built-in Game HUD graphic style library (Health Fill, Mana Glow, Damage Flash, Quest Outline, Coin Shine, Boss Alert); Missing trimmed; estimate 10–20 → 9–19 h. | +| 2026-11-10 | minor | G5: built-in Map Markers symbol library (Pin, Flag, Crosshair, Checkpoint; no default 9-slice); Missing trimmed; estimate 11–21 → 10–20 h. | +| 2026-11-10 | minor | G4 type: a right-click on type has Spelling › Auto Spell Check, checked while it is on, #4936; the Check Spelling and Edit Custom Dictionary dialogs remain; scores and estimates unchanged. | +| 2026-11-10 | minor | G4 type: a right-click on a word Auto Spell Check underlined lists its suggestions, Ignore All and Add to Dictionary, #4936; the Check Spelling and Edit Custom Dictionary dialogs remain; scores and estimates unchanged. | | 2026-11-10 | minor | G2: the Effect Gallery shows a thumbnail of each filter and a preview area inside the dialog (an original landscape drawing passed through the filter). Estimate 1–2 h → 0. The canvas preview and one-undo OK are unchanged. | | 2026-11-09 | minor | G4 type: Auto Spell Check (`edit.autoSpellCheck`) underlines the unknown words of the visible type, #4936; the Check Spelling and Edit Custom Dictionary dialogs and the right-click Spelling menu remain; scores and estimates unchanged. | | 2026-11-09 | minor | G5: built-in UI Frames symbol library (Panel, Button, Bar with default 9-slice); Missing trimmed; estimate 12–22 → 11–21 h. | diff --git a/docs/mcp.md b/docs/mcp.md index cb0157715b..a80d25f0be 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -1520,6 +1520,75 @@ the included files too. vectorcraft-cli run --cmd script.check --params '{"path": "Tidy Layers.jsx"}' ``` +`script.run {path? | source?, name?, args?, answers?, maxFuel?}` runs a JavaScript file against the open documents. +File › Scripts › Other Script… (Cmd+F12) picks a `.js` or `.jsx` file and runs it the same way; the help page +https://helpx.adobe.com/illustrator/desktop/automate-visualize-data/automate-actions/install-and-run-scripts.html +describes that menu item. Pass exactly one of `path` and `source`. A `path` must end in `.js` or `.jsx`, in any +case. A `.jsxbin` file or text that starts with `@JSXBIN@` is compiled and ends with an error, as does text that is +not UTF-8. The language is ES5.1. The script reaches the app through one global object: + +- `vc.run(id, params)` runs a command and returns its result. A command that fails throws an error the script can + catch. The documents and the session state the command changed, preferences included, go back, and any file it + wrote stays written and is named in the report. A result too large to cross throws a `RangeError`, and the + command's changes go back the same way. +- `vc.document` is a snapshot of the active document, or `null` when none is open. A snapshot too large to cross + throws a `RangeError`. +- `vc.commands` lists the commands a script may run. +- `vc.log(value)` adds a value to the report. +- `vc.args` is the `args` object. +- `vc.api.version` is `"1.0"`, and `vc.api.has(feature)` says whether the API has a feature. + +The run is one transaction. When the script ends, each document it changed gets one undo step named Run Script. A +run that changes no document adds no undo step. The journal records each command the run finished, as it records +commands run one at a time. A preference the run changed takes the run's value, and a preference changed in the app +while the run went on keeps that change. On an uncaught error, a limit or `script.stop`, every open document and the +session go back to their state before the run. A script can write files through the commands it runs, such as +export commands. A file written before the run failed stays on disk, and the error names it. A run from the menu +shows a warning first, unless you ticked Do not show this warning again or set the preference +`showExternalScriptWarning` to false. + +While a script runs, every other command that changes anything ends with the error `a script is running: stop it or +wait for it to finish`. MCP reports that error as JSON-RPC error `-32003`. `script.stop {}` stops the run and +returns `{stopped}`. `notifications/cancelled` stops a run only while the `tools/call` that started it is waiting +for it, as in a headless server; use `script.stop` for a run the app started. A script cannot run commands that +change anything outside the documents: `script.*` except `script.check`, `plugin.*`, `prefs.*`, `actionSet.*`, +`shortcutSet.*`, `help.*`, `print.*`, `library.*`, `importMatches.*`, `edit.undoGroup.*`, `file.recovery.*`, +`stroke.widthProfile.*`, saving, importing or deleting a preset, `text.addFontFiles`, `text.findFontFiles`, +`text.rescanFonts`, `links.findFiles`, `file.place.queue`, `color.loadProfile`, `color.removeProfile`, `file.print`, +`view.proofSetup`, `view.proofColors`, `view.overprintPreview` and `view.separationsPreview`. It also cannot run +`edit.clearHistory`: a run keeps each document's undo steps from before it and adds one. Calling one of these throws +an error. With Data Recovery off for complex documents, a run in the web build does not start while a complex document +has unsaved changes. + +VectorCraft sets these limits itself: + +| Limit | Value | +|-------|-------| +| Source text | 8 MiB | +| Heap | 256 MiB (128 MiB on the web) | +| Host calls | 2,000,000 | +| `maxFuel`, instructions in all | 1 to 100,000,000,000; 1,000,000,000 by default | +| Instructions without a pause | 200,000,000 | +| Nesting depth | 64 levels | +| A value crossing to or from a command | 16 MiB and 1,048,576 entries | +| `args` as JSON | 1 MiB | +| Log | 10,000 entries and 4 MiB | +| Growth before a person is asked | 100,000 objects and 512 MiB of new document data | + +In the app, a script past the growth limit stops at a question to continue or to stop and undo. Stop, Escape and +`ui.dialog.cancel` all stop the run. A run with nobody to ask, such as a call over MCP or the command line, ends +with an error at that limit. The headless reply is `{ok: true, name, changed, written, log, fuelUsed, hostCalls}`. +In the app the reply is `{running: true, name}`, and the report appears later as `scriptReport` in `ui.inspect`. +`answers` takes only an empty object, since scripts have no prompts yet. + +```json +{"name":"run_command","arguments":{"command":"script.run","params":{"source":"vc.run('shape.rectangle', {x: 0, y: 0, width: 10, height: 10});"}}} +``` + +```sh +vectorcraft-cli run --cmd script.run --params '{"path": "Tidy Layers.js", "args": {"margin": 12}}' +``` + ## Transparency and opacity masks Transparency and opacity-mask commands take `ids` (or `id`), so they need no selection. Opacity is a percentage @@ -2722,7 +2791,7 @@ as a value left out. ## Graphic style libraries Graphic style libraries are read-only sets of graphic styles generated in code (Shadows and Glows, Outlines and -Rules, Hand-Drawn, Gradient Finishes, Shape Effects, Blends and Transparency). `graphicStyle.libraries` lists them +Rules, Hand-Drawn, Gradient Finishes, Shape Effects, Blends and Transparency, Game HUD). `graphicStyle.libraries` lists them (`id`, `name`, `category`: `builtIn`, `user` or `loaded`, `count`) and `graphicStyle.library {library}` returns one's styles in the `graphicStyle.list` shape (`library` is an id or a name). `graphicStyle.addFromLibrary {library, name? | names?}` copies styles into the document's Graphic Styles as one undo step (no names: the whole library); styles the @@ -3255,11 +3324,13 @@ and `stroke.widthProfile.reset` removes every saved one. `stroke.set {profile}` ## Arrowheads -`stroke.set {startArrow, endArrow}` takes any of 40 generated heads by name (the params doc lists them; `null` for -none): arrows (`Arrow`, `Barbed`, `Concave`, `DoubleArrow`, `HalfArrowLeft`/`Right`, `Chevron`, `Feather`, +`stroke.set {startArrow, endArrow}` takes any of 41 generated heads by name (the params doc lists them; `null` for +none): arrows (`Arrow`, `LineArrow`, `Barbed`, `Concave`, `DoubleArrow`, `HalfArrowLeft`/`Right`, `Chevron`, `Feather`, `Swallowtail`…), filled and open shapes (`Triangle`, `Circle`, `Oval`, `Target`, `Tag`, `Diamond`, `Hexagon`, `Star`, the `…Open` rings…) and marks (`Bar`, `DoubleBar`, `DotOnBar`, `Slash`, `DoubleSlash`, `Bracket`, `Fork`, `Cross`, -`Plus`). Each head fits a box about four times its weight (stroke weight × `arrowScale`) long and wide. +`Plus`). Each head fits a box about four times its weight long and wide. A head's weight is the stroke weight scaled by +`arrowScale`, at least 0.25 pt. `LineArrow` has two arms of the head's weight (the line's weight at 100 % for lines of +0.25 pt or more) at right angles and spreads twice as wide. ## Stroke bounds and clicks @@ -4122,7 +4193,21 @@ every document they read except a native file and the native document that an SV `view.rotate {angle}` (desktop app) turns the view to `angle` degrees about the center of the canvas; a positive angle turns the art clockwise on screen. View › Rotate View and the status bar's angle menu run it. It returns `{angle}`, the -angle it set, normalized to (-180, 180], and `view.rotateReset` turns the view back to 0. +angle it set, normalized to (-180, 180], and `view.rotateReset` turns the view back to 0, returning `null` on success. + +Select the Rotate View Tool with `select_tool` and the tool id `rotateView`. Its `pointer_gesture` +drags turn the canvas about its center; Shift snaps to 15°. Document coordinates for a rotation +gesture use the view at the initial down event, including when the gesture spans several calls. +The control channel rejects malformed rotation packets without changing the angle and cancels +the current press. Start a new down event after an error. +Reset Rotate View is the command `view.rotateReset`: + +```json +{"name":"select_tool","arguments":{"tool":"rotateView"}} +{"name":"pointer_gesture","arguments":{"events":[{"kind":"down","x":300,"y":150},{"kind":"drag","x":200,"y":250},{"kind":"up","x":200,"y":250}]}} +{"name":"command_run","arguments":{"id":"view.rotateReset","params":{}}} +``` + `view.rotateToSelection` (desktop app, View › Rotate View to Selection) turns the view about the center of the canvas to the angle the selected objects share (`selectionRotation` in `document.inspect`, 0 when their angles differ), so their bounding box is square to the window. It returns `{angle}`, and with nothing selected it returns "nothing selected". @@ -5833,6 +5918,9 @@ undo step. Object › Transform › Scale, the Scale tool and the Transform pane `text.reshapePath {id, anchors: [[subpath, anchor]…], dx, dy}` does the same for the path of type on a path (Direct Selection dragging one of its anchors): the start and end brackets keep their fractions of the path and the text reflows along it. +`text.setPathHandle {id, subpath?, anchor, which: "in"|"out", x, y, independent?}` moves a direction handle of one +of its anchors, as `path.setHandle` moves a path's (Direct Selection dragging a handle of the path, #3565), in one +undo step. ```json {"name":"run_command","arguments":{"command":"text.reshapeArea","params":{"id":42,"anchors":[[0,2]],"dx":40,"dy":60}}} @@ -6057,7 +6145,7 @@ lines up to date as the type, the custom dictionary and the Ignore All words cha A right-click on an underlined word puts at the top of the canvas context menu the words `text.spelling.suggest` gives for it (each a `text.editRange {id, start, end, insert}` item labelled with its word), or No Suggestions, then Ignore All (`text.spelling.ignoreAll {word}`) and Add to Dictionary (`text.spelling.addWord {word}`); the context menu's -entries list them with their params. +entries list them with their params. A right-click on type also has Spelling › Auto Spell Check (`edit.autoSpellCheck`). ## Justification options diff --git a/docs/roadmap.md b/docs/roadmap.md index a0361d72a6..cc5c2a13ed 100644 --- a/docs/roadmap.md +++ b/docs/roadmap.md @@ -1,6 +1,6 @@ # Roadmap: milestones and what's next -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-10 · **Change:** minor (right-click on a word Auto Spell Check underlined: its suggestions, Ignore All and Add to Dictionary, #4936; previously minor: G2: Effect Gallery thumbnails and in-dialog preview are in; Auto Spell Check: `edit.autoSpellCheck` underlines the unknown words, #4936; previously minor: PDF editable import preserves authored ActualText once, including empty/nested spans and authored ordering (#6165); cross-line/style layout remains approximate; scores and estimates unchanged; PDF marked-text export (#6309): compatible glyphs stay on one layout line with per-glyph offsets; scores and estimates unchanged; interim macOS cursor delivery, #2292; native validation pending; scores and estimates unchanged; Control bar › Snapping includes the existing Snap to Glyph and Alignment Guides toggles (#6164); scores and estimates unchanged; custom dictionary and Ignore All: `text.spelling.addWord`, `removeWord`, `changeWord`, `dictionary` and `ignoreAll`, #4936; previously minor: EPS import: embedded fonts (composite, Type 42, CID-keyed, Type 1, CFF FontSet) draw their glyphs; spell check engine: `text.spelling.check` and `text.spelling.suggest` on craft-proof, #4936; previously minor: floating tab groups collapse into the side icon rail and opened rail panels fold back into it, #5925 in part; M4/M7: `.ai`/EPS type keeps its tab stops, and right-aligned lines with tabs lay out as the file's page, #6147; M4/M7: `.ai`/EPS type from the text document lays its lines out closer to the file's page, within limits, #6137; numeric fields step on wheel hover without taking keyboard focus, #5949; Character Styles panel: a double-click on a style's row opens its Character Style Options; the dialog keeps a fixed width and scrolls its sections, so its buttons stay on screen; Selection QoL: marquee modes and visible feedback, #5313; SVG CSS classes survive export and repeated import in all four styling modes (#2480); current-main integration retains event attributes and scripts; #3380 deletion-only review follow-up: independent survivors keep gradient placement, owned subpaths avoid discarded copies, and contracts/status/evidence are clarified; endpoint highlighting remains open; scores and estimates unchanged; Indian-language hyphenation review and license allowlist, #4947; Hindi catalog and contributor loanword preferences; full wording review in progress; Effect dialogs: a colour swatch beside a hex colour opens the Color Picker, #5365; shape tools move the selection from its centre point and turn it from the zone outside a box corner, #5477; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-10 · **Change:** minor (M10/G5: Game HUD graphic style library; previously minor: resizable icon-strip flyouts and bottom-aligned panel footers, #5713; previously minor: M10/G5: Map Markers built-in symbol library; previously minor: right-click on type: Spelling › Auto Spell Check, with its check mark, #4936; previously minor: right-click on a word Auto Spell Check underlined: its suggestions, Ignore All and Add to Dictionary, #4936; previously minor: G2: Effect Gallery thumbnails and in-dialog preview are in; Auto Spell Check: `edit.autoSpellCheck` underlines the unknown words, #4936; previously minor: PDF editable import preserves authored ActualText once, including empty/nested spans and authored ordering (#6165); cross-line/style layout remains approximate; scores and estimates unchanged; PDF marked-text export (#6309): compatible glyphs stay on one layout line with per-glyph offsets; scores and estimates unchanged; interim macOS cursor delivery, #2292; native validation pending; scores and estimates unchanged; Control bar › Snapping includes the existing Snap to Glyph and Alignment Guides toggles (#6164); scores and estimates unchanged; custom dictionary and Ignore All: `text.spelling.addWord`, `removeWord`, `changeWord`, `dictionary` and `ignoreAll`, #4936; previously minor: EPS import: embedded fonts (composite, Type 42, CID-keyed, Type 1, CFF FontSet) draw their glyphs; spell check engine: `text.spelling.check` and `text.spelling.suggest` on craft-proof, #4936; previously minor: floating tab groups collapse into the side icon rail and opened rail panels fold back into it, #5925 in part; M4/M7: `.ai`/EPS type keeps its tab stops, and right-aligned lines with tabs lay out as the file's page, #6147; M4/M7: `.ai`/EPS type from the text document lays its lines out closer to the file's page, within limits, #6137; numeric fields step on wheel hover without taking keyboard focus, #5949; Character Styles panel: a double-click on a style's row opens its Character Style Options; the dialog keeps a fixed width and scrolls its sections, so its buttons stay on screen; Selection QoL: marquee modes and visible feedback, #5313; SVG CSS classes survive export and repeated import in all four styling modes (#2480); current-main integration retains event attributes and scripts; #3380 deletion-only review follow-up: independent survivors keep gradient placement, owned subpaths avoid discarded copies, and contracts/status/evidence are clarified; endpoint highlighting remains open; scores and estimates unchanged; Indian-language hyphenation review and license allowlist, #4947; Hindi catalog and contributor loanword preferences; full wording review in progress; Effect dialogs: a colour swatch beside a hex colour opens the Color Picker, #5365; shape tools move the selection from its centre point and turn it from the zone outside a box corner, #5477; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x) > Numeric spinner update (2026-11-10): held mouse arrows repeat past the click timeout; scores and estimates unchanged (#6307). @@ -10,6 +10,8 @@ Numeric fields step on wheel hover without taking keyboard focus (#5949). Arrow Raster rendering fits and preflattens curved stroke outlines more tightly only below four times the raster tolerance, retaining thin-band coverage without changing stroke weight or vector export geometry. Current cached character/object outlines, cropped long strokes, gradient clips and effect rasters share the helper; cropped-region reuse and guarded flattening remain. The unchanged `fractional_curved_strokes_retain_coverage_between_notches` regression covers fractional weights, rotation, phase, opacity and f32-rounded endpoints. This is a quality/cost tradeoff, not a speed claim. Scores and estimates unchanged. +Icon-strip flyouts resize from the canvas-side edge and bottom, keeping the icon-column edge anchored (#5713). Independent group heights and flyout widths persist in workspaces; saved heights override content fitting while untouched heights still fit content. Shared panel button bars and the Glyphs font row stay at the bottom after enlargement; the Artboards list grows into the extra space. Regressions: `panel_docking::tests::glyphs_and_artboards_flyouts_keep_user_sizes` and `expanded_panel_footers_stay_at_the_bottom_with_short_and_long_lists`. Scores and estimates unchanged. + **PR #3273 revision — 2026-11-04:** Thin curved stroke coverage ported to the current raster-only cache, cropped-long-stroke and effect paths with guarded flattening; vector export geometry unchanged. Scores and estimates unchanged. Group Selection keeps an already selected component selected during a drag; a completed click still adds its next enclosing group. The current Direct Selection click/release machinery is shared, preserving compound-member picks, Shift deselection, isolation and masked-art dragging. Outline Stroke continues to preserve all original fills, including open contours; the change does not remove fills. Regressions: `group_selection_distinguishes_selected_leaf_drags_from_clicks` and `outline_fill_and_stroke_move_independently_with_group_selection` cover tool events, independent component movement and Undo/Redo. Scores and estimates unchanged. @@ -42,7 +44,6 @@ M7 type: Touch Type moves a right-to-left character along its line and up from i | Date | Change | Summary | |---|---|---| -| 2026-11-10 | minor | M7: right-click suggestions, Ignore All and Add to Dictionary on a word Auto Spell Check underlined (#4936); the dialogs remain; scores and estimates unchanged. | | 2026-11-07 | minor | M4/M7: `.ai`/EPS type from the text document keeps its paragraphs' tab stops, and right-aligned area type sets the text after a line's last tab against the right edge, the text before it at its stops from the left edge (#6147). Scores and estimates unchanged. | | 2026-11-07 | minor | M4/M7: `.ai`/EPS type from the text document keeps auto leading at the paragraph's share, the paragraph's hyphenation options and may show more of the last lines the file sets in an area frame of its own, when growing the frame by its lines' deepest descent plus 0.05 pt shows them, and a line a soft return ends is justified as a wrapped line is (#6137); a user's `.ai` that opened from its PDF part now opens from its layers. Limits: frames grow only for area type of one frame, horizontal, by its lines' deepest descent plus 0.05 pt; type in a font that isn't installed, and hyphenation in a language that isn't imported, still lay out differently. Scores and estimates unchanged. | | 2026-11-08 | minor | Character Styles panel: a double-click on a user style's row opens its Character Style Options (`ui.charStyleOptions`); the dialog keeps a fixed width and scrolls its sections in a shorter window, so OK and Cancel stay on screen. Tests `panels::text_styles::tests::double_clicking_a_character_style_row_opens_its_options` and `dialogs::char_style_options::tests::the_sections_scroll_in_a_window_shorter_than_the_general_list`. Scores and estimates unchanged. | @@ -51,6 +52,7 @@ M7 type: Touch Type moves a right-to-left character along its line and up from i | 2026-11-02 | minor | Selection QoL: saved marquee modes, screen drag direction with a 3 px dead zone, and translated mode/E feedback (#5313); VectorCraft addition, scores and estimates unchanged. | | 2026-11-07 | minor | Indian-language hyphenation (#4947): eleven MIT-licensed pattern sets, with grapheme and shaping-cluster protection in both composers and existing paragraph limits. Assamese and Sanskrit are selectable; Sanskrit automatic patterns remain pending an allowlisted source. Scores and estimates unchanged. | | 2026-11-05 | minor | Effect dialogs: a colour swatch beside a hex colour field follows typed values, and a double-click opens the Color Picker over the dialog, whose OK fills the field (#5365); scores and estimates unchanged. | +| 2026-11-06 | minor | Icon-strip flyouts resize on their free edges and retain sizes with workspaces (#5713); saved heights beat auto-fit; panel footers stay at the bottom after enlargement. Scores and estimates unchanged. | | 2026-11-05 | minor | Selection Tools add-on: Select Linked, Embedded, Missing and Modified select the images and placed documents with that link status (Object › Plug-ins › Selection Tools and the Links panel menu; Shift adds), and Select by Link Status… lists them by name, status and format to pick from, optionally zooming to them; what is hidden, locked, on a template layer or outside the isolated group is left out and the status bar says how many (#5526, a VectorCraft addition); scores and estimates unchanged (estimated). | | 2026-11-05 | minor | Pencil and Paintbrush: a new stroke with Keep selected off leaves nothing selected, the earlier selection included, while Keep selected on selects only the new path (#5752); scores and estimates unchanged. | | 2026-11-05 | minor | Layers panel: a layer whose Layer Options › Print is off shows its name italic, as the reference application shows non-printing layers, and keeps it while the row is dragged (#5739); scores and estimates unchanged. | @@ -140,23 +142,23 @@ native wording review, layout checks and a web Devanagari font remain. [Notes](l | M3 | Paint & appearance (swatches, color, gradient, stroke, appearance, transparency, styles) | ✅ done (M3.7–M3.98): swatches, groups, libraries, tints, Lab spots and Registration; Eyedropper styles highlighted text only (atomic transparency rejection); Eyedropper reads visible locked and outside-isolation sources (#1251); Color Picker, Color panel, Color Guide, Color Themes, Edit Colors and Recolor Artwork (screen-bounded Edit chip list, #3416); gradients that follow every transform, the annotator, linked stops, freeform gradients, focal points, gradients on strokes and Expand; visible strokes when paint is added to inherited None/zero-width art (#1253); stroke geometry, arrowheads, dashes fitted to corners, stroke on type, width profiles and the Width tool (Shift-double-click enables adjoining adjustment in Width Point Edit), Scale Strokes and preview bounds; Appearance targeting, container appearance, target circles, Expand Appearance; knockout, isolation, blend accuracy, CMYK blending, overprint, Attributes, masks and clipping, Flatten Transparency; graphic styles, links and libraries; CSS library export preserves fractional linear and radial gradient stop positions. Left: freeform gradients in SVG/PDF, mixed spot/process gradients in SVG and PDF gradients mixing a spot color with RGB or Lab stops export as stops or process colors; PDF export writes dithered gradient fills with spot stops, and Perceptual spot gradients with RGB or Lab stops other than white or more than 4,096 stops on their curve, as images in process colors; confirm the Scale Strokes & Effects default | 4–8 | | M5 | Performance | 🟡 background render + caches + MT done; `vectorcraft-cli bench` and `vectorcraft-cli perf` (budget suite); opaque solid-fill knockout paths draw once in hard-edge/supersampled raster export, with analytical-AA compositing unchanged; file format v2 opens 3× faster (50k paths: 722 → 244 ms); raster effects (glows, shadows, blur, feather) no longer force the whole frame single-threaded (filtered offscreen per effect, verified equal to the single-threaded reference); Craquelure/Mosaic Tiles/Stained Glass distance searches optimized with pixel-invariance checks and the `texture_drag_perf` probe (#1257); effect-heavy demos need a clean-machine benchmark; dirty-region rendering, GPU backend spike pending | 15–25 | | M6 | Path operations (Pathfinder, Shape Builder, offset…) | ✅ mostly done (live compound shapes: Make, Alt-click a Shape Mode, member modes, Release, Expand (#4522); single-result Pathfinder names and SVG IDs retained (#1293); Divide open-cutting-path geometry, appearance and history verified (#1307; existing segment cap remains); Simplify preview/counts and rewritten-path component selection verified (#1272; the slider opens at the Auto-Simplify level; a Direct Selection part of a path simplifies on its own); Compound appearance and member fill-rule edits verified (#1197); Boolean precision on almost-horizontal edges fixed and the property tests made deterministic; Shape Builder gap detection, large-offset bug open); Shape Builder Gap Detection shares Live Paint’s spatial gap finder and temporary merge bridges (#2526); Custom is capped at 72 pt in the existing options dialog | 3–6 | -| M7 | Type (point/area/path, editing, styles, OpenType, threading, glyphs) | Spell check engine: `text.spelling.check` and `text.spelling.suggest` on craft-proof and the custom dictionary and Ignore All commands and Auto Spell Check with its right-click suggestions, Ignore All and Add to Dictionary (#4936; the dialogs remain); Right-aligned area type sets the text after a line's last tab against the right edge, the text before it at its stops (#6147); A line a soft return ends is justified as a wrapped line is (#6137); Indian-language pattern hyphenation preserves syllables in both composers (#4947); 🟡 Hanging punctuation keeps its published amounts under Glyph Scaling, and Standard burasagari counts a hung line start as room; Fullwidth `!` / `?` keep an upright fallback in vertical type; Document-point character controls after object/group scaling (#1034; optional font-size preservation remains separate), Character/Paragraph Styles (explicit Auto-leading resets and local leading overrides), per-paragraph paragraph attributes, mixed paragraph alignment indication (headless regressions, full integration CI and visual review pass), Area Type Options (with Width/Height, Auto Size and Shrink Text to Fit; overflow reported to agents and vertical Align), type areas resized by their handles and reshaped with Direct Selection, threaded text, Fit Headline, Glyphs, OpenType panel (including font-defined Stylistic Sets), Find Font (Document, Recent and System replacement sources, #5217), installed system fonts in every font menu (fonts registered with Windows outside its font folders, the XDG and Flatpak host font folders on Linux, and fonts installed while the app runs, listed when it comes back to the front; searchable; the Character and Properties menus show each family's sample of the selected text, preview it live under the pointer or ↑/↓, show recently applied families first (#3515), filter by script and kind, list a family's styles, and star favourites; the Glyphs panel and Find Font's Replace With use the same menu without the live preview) and found by name on open/import (full-name aliases and Missing Fonts searches verified, #1258; Windows font-service QA pending), variable fonts' named instances as styles, CJK names in the UI, input methods (marked text in place, candidate window at the caret; Japanese IME), Text Wrap (offset, invert, both sides of an object; follows edits), Type on a Path effects and Options with draggable start/centre/end brackets (slide, flip), tab stops + Tabs panel (Above Text floats it over the selected text, its ruler at the canvas zoom so stops line up with the columns, #729), inline symbols in text (beyond parity), Hebrew/Arabic bidirectional text, Paragraph Direction, Every-line/Single-line Composer per object (ragged text too) done; paint-only Arabic harakat keep joining with GDEF-mark ownership and Insert Kashidas tatweels on the base letter's paint (`tests::harakat`); tab leaders, spell check, vertical type pending | 45–60 | -| M7 | Type (point/area/path, editing, styles, OpenType, threading, glyphs) | Spell check engine: `text.spelling.check` and `text.spelling.suggest` on craft-proof and the custom dictionary and Ignore All commands and Auto Spell Check with its right-click suggestions, Ignore All and Add to Dictionary (#4936; the dialogs remain); Right-aligned area type sets the text after a line's last tab against the right edge, the text before it at its stops (#6147); A line a soft return ends is justified as a wrapped line is (#6137); Indian-language pattern hyphenation preserves syllables in both composers (#4947); 🟡 Fullwidth `!` / `?` keep an upright fallback in vertical type; Hyphenation… and Justification… per paragraph (#2310, #2755), Auto Leading also driving the Character panel's Leading, the Alt+↑/↓ leading nudge and Fill with Placeholder Text; Document-point character controls after object/group scaling (#1034; optional font-size preservation remains separate), Character/Paragraph Styles (explicit Auto-leading resets and local leading overrides), per-paragraph paragraph attributes, mixed paragraph alignment indication (headless regressions, full integration CI and visual review pass), Area Type Options (with Width/Height, Auto Size and Shrink Text to Fit; overflow reported to agents and vertical Align), type areas resized by their handles and reshaped with Direct Selection, threaded text, Fit Headline, Glyphs, OpenType panel, Find Font (Document, Recent and System replacement sources, #5217), installed system fonts in every font menu (fonts registered with Windows outside its font folders, the XDG and Flatpak host font folders on Linux, and fonts installed while the app runs, listed when it comes back to the front; searchable; the Character and Properties menus show each family's sample of the selected text, preview it live under the pointer or ↑/↓, filter by script and kind, list a family's styles, and star favourites; the Glyphs panel and Find Font's Replace With use the same menu without the live preview) and found by name on open/import (full-name aliases and Missing Fonts searches verified, #1258; Windows font-service QA pending), variable fonts' named instances as styles, CJK names in the UI, input methods (marked text in place, candidate window at the caret; Japanese IME), Text Wrap (offset, invert, both sides of an object; follows edits), Type on a Path effects and Options with draggable start/centre/end brackets (slide, flip), tab stops + Tabs panel (Above Text floats it over the selected text, its ruler at the canvas zoom so stops line up with the columns, #729), inline symbols in text (beyond parity), Hebrew/Arabic bidirectional text, Paragraph Direction, Every-line/Single-line Composer per object (ragged text too) done; paint-only Arabic harakat keep joining with GDEF-mark ownership and Insert Kashidas tatweels on the base letter's paint (`tests::harakat`); tab leaders, spell check, vertical type pending | 45–60 | -| M7 | Type (point/area/path, editing, styles, OpenType, threading, glyphs) | Spell check engine: `text.spelling.check` and `text.spelling.suggest` on craft-proof and the custom dictionary and Ignore All commands and Auto Spell Check with its right-click suggestions, Ignore All and Add to Dictionary (#4936; the dialogs remain); Right-aligned area type sets the text after a line's last tab against the right edge, the text before it at its stops (#6147); A line a soft return ends is justified as a wrapped line is (#6137); Indian-language pattern hyphenation preserves syllables in both composers (#4947); 🟡 Fullwidth `!` / `?` keep an upright fallback in vertical type; Document-point character controls after object/group scaling (#1034; optional font-size preservation remains separate), Character/Paragraph Styles (explicit Auto-leading resets and local leading overrides), per-paragraph paragraph attributes, mixed paragraph alignment indication (headless regressions, full integration CI and visual review pass), Area Type Options (with Width/Height, Auto Size and Shrink Text to Fit; overflow reported to agents and vertical Align), type areas resized by their handles and reshaped with Direct Selection, threaded text, Fit Headline, Glyphs, OpenType panel, Find Font (Document, Recent and System replacement sources, #5217), installed system fonts in every font menu (fonts registered with Windows outside its font folders, the XDG and Flatpak host font folders on Linux, and fonts installed while the app runs, listed when it comes back to the front; searchable; the Character and Properties menus show each family's sample of the selected text, preview it live under the pointer or ↑/↓, show recently applied families first (#3515), filter by script and kind, list a family's styles, and star favourites; the Glyphs panel and Find Font's Replace With use the same menu without the live preview) and found by name on open/import (full-name aliases and Missing Fonts searches verified, #1258; Windows font-service QA pending), variable fonts' named instances as styles, CJK names in the UI, input methods (marked text in place, candidate window at the caret; Japanese IME), Text Wrap (offset, invert, both sides of an object; follows edits), Type on a Path effects and Options with draggable start/centre/end brackets (slide, flip), tab stops + Tabs panel (Above Text floats it over the selected text, its ruler at the canvas zoom so stops line up with the columns, #729), inline symbols in text (beyond parity), Hebrew/Arabic bidirectional text, Paragraph Direction, Every-line/Single-line Composer per object (ragged text too) done; paint-only Arabic harakat keep joining with GDEF-mark ownership and Insert Kashidas tatweels on the base letter's paint (`tests::harakat`); tab leaders, spell check, vertical type pending | 45–60 | +| M7 | Type (point/area/path, editing, styles, OpenType, threading, glyphs) | Spell check engine: `text.spelling.check` and `text.spelling.suggest` on craft-proof and the custom dictionary and Ignore All commands and Auto Spell Check with its right-click suggestions, Ignore All and Add to Dictionary, and Spelling › Auto Spell Check in the context menu of type (#4936; the dialogs remain); Right-aligned area type sets the text after a line's last tab against the right edge, the text before it at its stops (#6147); A line a soft return ends is justified as a wrapped line is (#6137); Indian-language pattern hyphenation preserves syllables in both composers (#4947); 🟡 Hanging punctuation keeps its published amounts under Glyph Scaling, and Standard burasagari counts a hung line start as room; Fullwidth `!` / `?` keep an upright fallback in vertical type; Document-point character controls after object/group scaling (#1034; optional font-size preservation remains separate), Character/Paragraph Styles (explicit Auto-leading resets and local leading overrides), per-paragraph paragraph attributes, mixed paragraph alignment indication (headless regressions, full integration CI and visual review pass), Area Type Options (with Width/Height, Auto Size and Shrink Text to Fit; overflow reported to agents and vertical Align), type areas resized by their handles and reshaped with Direct Selection, threaded text, Fit Headline, Glyphs, OpenType panel (including font-defined Stylistic Sets), Find Font (Document, Recent and System replacement sources, #5217), installed system fonts in every font menu (fonts registered with Windows outside its font folders, the XDG and Flatpak host font folders on Linux, and fonts installed while the app runs, listed when it comes back to the front; searchable; the Character and Properties menus show each family's sample of the selected text, preview it live under the pointer or ↑/↓, show recently applied families first (#3515), filter by script and kind, list a family's styles, and star favourites; the Glyphs panel and Find Font's Replace With use the same menu without the live preview) and found by name on open/import (full-name aliases and Missing Fonts searches verified, #1258; Windows font-service QA pending), variable fonts' named instances as styles, CJK names in the UI, input methods (marked text in place, candidate window at the caret; Japanese IME), Text Wrap (offset, invert, both sides of an object; follows edits), Type on a Path effects and Options with draggable start/centre/end brackets (slide, flip), tab stops + Tabs panel (Above Text floats it over the selected text, its ruler at the canvas zoom so stops line up with the columns, #729), inline symbols in text (beyond parity), Hebrew/Arabic bidirectional text, Paragraph Direction, Every-line/Single-line Composer per object (ragged text too) done; paint-only Arabic harakat keep joining with GDEF-mark ownership and Insert Kashidas tatweels on the base letter's paint (`tests::harakat`); tab leaders, spell check, vertical type pending | 45–60 | +| M7 | Type (point/area/path, editing, styles, OpenType, threading, glyphs) | Spell check engine: `text.spelling.check` and `text.spelling.suggest` on craft-proof and the custom dictionary and Ignore All commands and Auto Spell Check with its right-click suggestions, Ignore All and Add to Dictionary, and Spelling › Auto Spell Check in the context menu of type (#4936; the dialogs remain); Right-aligned area type sets the text after a line's last tab against the right edge, the text before it at its stops (#6147); A line a soft return ends is justified as a wrapped line is (#6137); Indian-language pattern hyphenation preserves syllables in both composers (#4947); 🟡 Fullwidth `!` / `?` keep an upright fallback in vertical type; Hyphenation… and Justification… per paragraph (#2310, #2755), Auto Leading also driving the Character panel's Leading, the Alt+↑/↓ leading nudge and Fill with Placeholder Text; Document-point character controls after object/group scaling (#1034; optional font-size preservation remains separate), Character/Paragraph Styles (explicit Auto-leading resets and local leading overrides), per-paragraph paragraph attributes, mixed paragraph alignment indication (headless regressions, full integration CI and visual review pass), Area Type Options (with Width/Height, Auto Size and Shrink Text to Fit; overflow reported to agents and vertical Align), type areas resized by their handles and reshaped with Direct Selection, threaded text, Fit Headline, Glyphs, OpenType panel, Find Font (Document, Recent and System replacement sources, #5217), installed system fonts in every font menu (fonts registered with Windows outside its font folders, the XDG and Flatpak host font folders on Linux, and fonts installed while the app runs, listed when it comes back to the front; searchable; the Character and Properties menus show each family's sample of the selected text, preview it live under the pointer or ↑/↓, filter by script and kind, list a family's styles, and star favourites; the Glyphs panel and Find Font's Replace With use the same menu without the live preview) and found by name on open/import (full-name aliases and Missing Fonts searches verified, #1258; Windows font-service QA pending), variable fonts' named instances as styles, CJK names in the UI, input methods (marked text in place, candidate window at the caret; Japanese IME), Text Wrap (offset, invert, both sides of an object; follows edits), Type on a Path effects and Options with draggable start/centre/end brackets (slide, flip), tab stops + Tabs panel (Above Text floats it over the selected text, its ruler at the canvas zoom so stops line up with the columns, #729), inline symbols in text (beyond parity), Hebrew/Arabic bidirectional text, Paragraph Direction, Every-line/Single-line Composer per object (ragged text too) done; paint-only Arabic harakat keep joining with GDEF-mark ownership and Insert Kashidas tatweels on the base letter's paint (`tests::harakat`); tab leaders, spell check, vertical type pending | 45–60 | +| M7 | Type (point/area/path, editing, styles, OpenType, threading, glyphs) | Spell check engine: `text.spelling.check` and `text.spelling.suggest` on craft-proof and the custom dictionary and Ignore All commands and Auto Spell Check with its right-click suggestions, Ignore All and Add to Dictionary, and Spelling › Auto Spell Check in the context menu of type (#4936; the dialogs remain); Right-aligned area type sets the text after a line's last tab against the right edge, the text before it at its stops (#6147); A line a soft return ends is justified as a wrapped line is (#6137); Indian-language pattern hyphenation preserves syllables in both composers (#4947); 🟡 Fullwidth `!` / `?` keep an upright fallback in vertical type; Document-point character controls after object/group scaling (#1034; optional font-size preservation remains separate), Character/Paragraph Styles (explicit Auto-leading resets and local leading overrides), per-paragraph paragraph attributes, mixed paragraph alignment indication (headless regressions, full integration CI and visual review pass), Area Type Options (with Width/Height, Auto Size and Shrink Text to Fit; overflow reported to agents and vertical Align), type areas resized by their handles and reshaped with Direct Selection, threaded text, Fit Headline, Glyphs, OpenType panel, Find Font (Document, Recent and System replacement sources, #5217), installed system fonts in every font menu (fonts registered with Windows outside its font folders, the XDG and Flatpak host font folders on Linux, and fonts installed while the app runs, listed when it comes back to the front; searchable; the Character and Properties menus show each family's sample of the selected text, preview it live under the pointer or ↑/↓, show recently applied families first (#3515), filter by script and kind, list a family's styles, and star favourites; the Glyphs panel and Find Font's Replace With use the same menu without the live preview) and found by name on open/import (full-name aliases and Missing Fonts searches verified, #1258; Windows font-service QA pending), variable fonts' named instances as styles, CJK names in the UI, input methods (marked text in place, candidate window at the caret; Japanese IME), Text Wrap (offset, invert, both sides of an object; follows edits), Type on a Path effects and Options with draggable start/centre/end brackets (slide, flip), tab stops + Tabs panel (Above Text floats it over the selected text, its ruler at the canvas zoom so stops line up with the columns, #729), inline symbols in text (beyond parity), Hebrew/Arabic bidirectional text, Paragraph Direction, Every-line/Single-line Composer per object (ragged text too) done; paint-only Arabic harakat keep joining with GDEF-mark ownership and Insert Kashidas tatweels on the base letter's paint (`tests::harakat`); tab leaders, spell check, vertical type pending | 45–60 | | M8 | Transform & distort (Puppet Warp, Liquify tools, Envelopes, Blends, Perspective Grid) | ✅ done (M8.1–M8.20 on 2026-10-06, fidelity pass): Liquify Tool Options with one shared brush, pen pressure, hold-to-apply, a safe scope and incremental strokes; tool options that last; Puppet Warp rotation, multi-select, Control bar and a rest-shape session that follows Undo; Width tool on compound paths; Envelope dialogs with preview, Reset with Warp/Mesh, full Envelope Options, type/images/symbols/appearance/gradients/patterns distorted on canvas and in every export, warps that keep their frame, Edit Contents, mesh handles and Control bar; Blend Options, anchor-targeted Blend tool, editable spine, keys picked on the canvas, faithful interpolation and knockout; Anchor Point spine conversion/handle editing and selection priority (#2544), with #2425 Shift reshape preserved; Perspective Grid with Define Grid, presets, lock/snap/rulers, widgets, the 1–4 plane switch, movable planes, Perspective Selection scale/copy/perpendicular/Transform Again, and type and symbols truly projected with Edit Text. Left: Anti-Alias and Preserve Shape output, warp-envelope point editing, brush interpolation in blends, Free Transform/Scale/Reflect along a rotated box | 2–4 | | M9 | Live effects (+ 3D & Materials) | 🟡 2D effects done incl. Effect → Pathfinder, Color Adjustments and Document Raster Effects Settings; PDF export warns when the pixel cap lowers raster-effect resolution; Artistic › Colored Pencil, Cutout, Dry Brush, Film Grain, Fresco, Neon Glow, Paint Daubs, Palette Knife, Poster Edges, Rough Pastels, Smudge Stick, Sponge, Underpainting and Watercolor and Sketch › Halftone Pattern, Bas Relief, Charcoal, Conté Crayon, Photocopy, Stamp, Torn Edges and Water Paper done (57/57 Photoshop filters); Revolve with automatic smooth vector shading, default-on circular caps and continuous rims, Extrude & Bevel, Inflate and Rotate with one to ten colored directional lights and four original lighting presets; SVG Filters, remaining raster effects and 3D materials and shadows pending | 81–130 | -| M10 | Brushes, symbols, patterns, Repeat | 🟡 pattern swatches (5 tile types, Pattern Options, editing mode, SVG `<pattern>`/PDF export) and live Repeat (radial/grid/mirror) done; interactive selected mirror axis implemented (focused and native checks passed; full CI blocked by an unrelated text test); symbol libraries done (Window › Symbol Libraries, a generated Basic Shapes library, User Defined, Other Library…, Save Symbols); brush libraries done (Window › Brush Libraries, four generated libraries, User Defined, Other Library…, Save Brushes); symbol editing shows draggable 9-slice guides (#5280), with guides outside the artwork still unsupported; brushes/symbols in progress | 23–37 | +| M10 | Brushes, symbols, patterns, Repeat | 🟡 pattern swatches (5 tile types, Pattern Options, editing mode, SVG `<pattern>`/PDF export) and live Repeat (radial/grid/mirror) done; interactive selected mirror axis implemented (focused and native checks passed; full CI blocked by an unrelated text test); symbol libraries done (Window › Symbol Libraries, three generated libraries (Basic Shapes, UI Frames, Map Markers), User Defined, Other Library…, Save Symbols); brush libraries done (Window › Brush Libraries, four generated libraries, User Defined, Other Library…, Save Brushes); symbol editing shows draggable 9-slice guides (#5280), with guides outside the artwork still unsupported; brushes/symbols in progress | 23–37 | | M11 | Artboards & views (selected-set deletion shared by Artboards menu, trash and Properties, retaining artboard 1 when all are selected; Artboard deletion keys keep the first of an all-selected set and protect artwork; history prunes invalid indices while preserving valid multiselection (history tests and full workspace CI pass); click-to-fit objects with the Artboard tool (#1227), artboard escape routing and document setup modal handoff done; artboard panel/tool with Move Artwork for X/Y fields and Artboard Options, Trim View, middle-button pan, print tiling and the status bar's artboard navigator with synchronized Artboard tool selection done; multiple windows, presentation polish) (cached canvas reprojection preserves scale during resize, rotation and DPI changes; regression-tested and contributor-confirmed 2026-10-19; estimates unchanged) (cached canvas dimensions match the renderer limit before cache-key creation, view construction and worker submission; regression-tested; estimates unchanged) | 🟡; Artboard Options shares existing presets and orientation controls and can fit artwork without moving it; artwork fitting includes all drawn document art across artboards and off-board; artwork bounds are cached by active document and revision, and selection uses the shared bounds cache across artboards | 15–25 | | M10 | Brushes, symbols, patterns, Repeat | 🟡 pattern swatches (5 tile types, Pattern Options, editing mode, SVG `<pattern>`/PDF export) and live Repeat (radial/grid/mirror) done; interactive selected mirror axis implemented (focused and native checks passed; full CI blocked by an unrelated text test); symbol and brush libraries done; symbol editing shows draggable 9-slice guides (#5280), with guides outside the artwork still unsupported; brushes/symbols in progress | 23–37 | | M11 | Artboards & views (selected-set deletion shared by Artboards menu, trash and Properties, retaining artboard 1 when all are selected; Artboard deletion keys keep the first of an all-selected set and protect artwork; history prunes invalid indices while preserving valid multiselection (history tests and full workspace CI pass); click-to-fit objects with the Artboard tool (#1227), artboard escape routing and document setup modal handoff done; artboard panel/tool with Move Artwork for X/Y fields and Artboard Options, Trim View, middle-button pan, print tiling and the status bar's artboard navigator with synchronized Artboard tool selection done; multiple windows, presentation polish) (cached canvas reprojection preserves scale during resize, rotation and DPI changes; regression-tested and contributor-confirmed 2026-10-19; estimates unchanged) (cached canvas dimensions match the renderer limit before cache-key creation, view construction and worker submission; regression-tested; estimates unchanged); status-bar pointer coordinates follow the active ruler origin and General units | 🟡; Artboard Options shares existing presets and orientation controls and can fit artwork without moving it; artwork fitting includes all drawn document art across artboards and off-board; artwork bounds are cached by active document and revision, and selection uses the shared bounds cache across artboards | 15–25 | -| M10 | Brushes, symbols, patterns, Repeat | 🟡 pattern swatches (5 tile types, Pattern Options, editing mode, SVG `<pattern>`/PDF export) and live Repeat (radial/grid/mirror) done; interactive selected mirror axis implemented (focused and native checks passed; full CI blocked by an unrelated text test); symbol libraries done (Window › Symbol Libraries, a generated Basic Shapes library, User Defined, Other Library…, Save Symbols); brush libraries done (Window › Brush Libraries, four generated libraries, User Defined, Other Library…, Save Brushes); brushes/symbols in progress | 23–37 | +| M10 | Brushes, symbols, patterns, Repeat | 🟡 pattern swatches (5 tile types, Pattern Options, editing mode, SVG `<pattern>`/PDF export) and live Repeat (radial/grid/mirror) done; interactive selected mirror axis implemented (focused and native checks passed; full CI blocked by an unrelated text test); symbol libraries done (Window › Symbol Libraries, three generated libraries (Basic Shapes, UI Frames, Map Markers), User Defined, Other Library…, Save Symbols); brush libraries done (Window › Brush Libraries, four generated libraries, User Defined, Other Library…, Save Brushes); brushes/symbols in progress | 23–37 | | M11 | Artboards & views (selected-set deletion shared by Artboards menu, trash and Properties, retaining artboard 1 when all are selected; Artboard deletion keys keep the first of an all-selected set and protect artwork; history prunes invalid indices while preserving valid multiselection (history tests and full workspace CI pass); click-to-fit objects with the Artboard tool (#1227), artboard escape routing and document setup modal handoff done; artboard panel/tool with Move Artwork for X/Y fields and Artboard Options, Trim View, middle-button pan, print tiling and the status bar's artboard navigator with synchronized Artboard tool selection done; Window › Arrange › Tile and Consolidate All Windows done; multiple windows, presentation polish) (cached canvas reprojection preserves scale during resize, rotation and DPI changes; regression-tested and contributor-confirmed 2026-10-19; estimates unchanged) (cached canvas dimensions match the renderer limit before cache-key creation, view construction and worker submission; regression-tested; estimates unchanged) | 🟡; Artboard Options shares existing presets and orientation controls and can fit artwork without moving it; artwork fitting includes all drawn document art across artboards and off-board; artwork bounds are cached by active document and revision, and selection uses the shared bounds cache across artboards | 15–25 | | M10 | Brushes, symbols, patterns, Repeat | 🟡 pattern swatches (5 tile types, Pattern Options, editing mode, SVG `<pattern>`/PDF export) and live Repeat (radial/grid/mirror) done; interactive selected mirror axis implemented (focused and native checks passed; full CI blocked by an unrelated text test); symbol and brush libraries done; brushes/symbols in progress | 23–37 | | M11 | Artboards & views (selected-set deletion shared by Artboards menu, trash and Properties, retaining artboard 1 when all are selected; Artboard deletion keys keep the first of an all-selected set and protect artwork; history prunes invalid indices while preserving valid multiselection (history tests and full workspace CI pass); click-to-fit objects with the Artboard tool (#1227), artboard escape routing and document setup modal handoff done; artboard panel/tool with Move Artwork for X/Y fields and Artboard Options, Trim View, middle-button pan, print tiling and the status bar's artboard navigator with synchronized Artboard tool selection done; Window › Arrange › Tile and Consolidate All Windows done; multiple windows, presentation polish) (cached canvas reprojection preserves scale during resize, rotation and DPI changes; regression-tested and contributor-confirmed 2026-10-19; estimates unchanged) (cached canvas dimensions match the renderer limit before cache-key creation, view construction and worker submission; regression-tested; estimates unchanged); status-bar pointer coordinates follow the active ruler origin and General units | 🟡; Artboard Options shares existing presets and orientation controls and can fit artwork without moving it; artwork fitting includes all drawn document art across artboards and off-board; artwork bounds are cached by active document and revision, and selection uses the shared bounds cache across artboards | 15–25 | | M12 | Advanced color & art (CMYK/ICC, separations, Gradient Mesh, Live Paint, Image Trace, Graphs) | 🟡 Gradient Mesh, Live Paint, Image Trace (junction-returning pieces retain their positioned boundaries; a simpler contour walk with identical output; an edge's sub-pixel shift is the same from either side; notches read only their own piece; collapsed loops keep few segments; large images trace with a warning; Auto Color keeps rare distinct colours; quick presets trace at once and the Image Trace button opens the adjustment controls; Properties reopens them; tiny fitted contours retain islands and holes; Create Strokes: exact crop EDT, Guo–Hall thinning and maximal-disc graph simplification; 15 presets, the 14 documented ones each with an enhanced version; Ignore Color, Shapes, Auto Grouping and Gradients options; measured in `image-trace-quality.md`; closed outlines retain their interior after straightening; the Flat Logo mode places edges to a fraction of a pixel, restores sharp corners, snaps lines and circles, and refuses gradients; live trace result bounds and selection highlights exclude the retained bitmap except in source-image views), Recolor Artwork, colour management (ICC, soft proofing, separations preview), Graphs (all 9 tools, Graph Data/Type, group-selected series colours persist through regenerate/save/open) done; Graph Design and Marker designs, Transpose and Switch x/y, `\|` label line breaks, the pie options, drop shadows, the legend across the top, overlapping widths, First Row/Column in Front, filled lines, kept label formatting and the Graph Data worksheet done; graph Column designs pending | 6–10 | -| M13 | Automation (Actions ✅ record/playback, persisted; variables, scripting, batch) | 🟡 MCP `add_text` exposes existing vertical point, area and path type; broader scripting and batch work remains | 18–27 | +| M13 | Automation (Actions ✅ record/playback, persisted; variables, scripting, batch) | 🟡 MCP `add_text` exposes existing vertical point, area and path type; `script.run` and File › Scripts › Other Script… run JavaScript files; the script document model and console and batch work remain | 18–27 | | M13 | Automation (Actions ✅ record/playback, persisted; variables, scripting, batch) | 🟡 | 18–27 | -| M14 | 1.0 polish (preferences, shortcut editor, workspaces, accessibility, packaging for all OSes) (status messages and readouts use stable responsive allocations sized for localized labels and ordinary coordinates; sample widths cached by language/unit/DPI; regression-tested and contributor-confirmed 2026-10-19; estimates unchanged) | 🟡 Interim macOS cursor delivery (#2292) uses existing artwork and host-owned AppKit cursors; headless coverage only, native menu/focus/handback and display validation pending. Dock groups collapse to their tabs by a double-click on a tab (UI.8); Preferences › General › Constrain Angle acts for the arrow keys, Shift drags and new objects (#394, 2026-10-21); numeric-field pointer selection and focus regression-tested (#1326, in part; short movements still select all); RPM runtime capabilities and glibc floor checked (#1275; real-distro install/start-up pending), Eyedropper cursor with precise-setting checks (#1269), Preferences, shortcut editor (chords with Shift and a punctuation key fire as typed; other apps' text shortcut sets imported), workspaces (each keeps its layout changes until Reset <name>, UI.7), Window › Help Bar shown or hidden apart from the status bar and kept in saved workspaces, panels docked by dragging into any dock group (as tabs or a top/bottom split) or into the icon column, and closed from a dock tab's context menu (UI.6), a custom title bar on Windows/Linux with a Home button, content-sized dialogs, menus that scroll when longer than the window and macOS native menu dismissal done (M14.8), and native macOS save sheets with a Format menu (#866); titled PDF exports set `DisplayDocTitle` for viewers and accessibility checkers (#3646); accessibility and broader Windows/Linux packaging/QA pending; floating tab groups collapse into the side icon rail and opened rail panels fold back into it (#5925, in part), with pointer and native-window regression coverage; estimates unchanged; numeric spinner arrows keep repeating while held with the mouse (#6307) | 18–28 | +| M14 | 1.0 polish (preferences, shortcut editor, workspaces, accessibility, packaging for all OSes) (status messages and readouts use stable responsive allocations sized for localized labels and ordinary coordinates; sample widths cached by language/unit/DPI; regression-tested and contributor-confirmed 2026-10-19; estimates unchanged) | 🟡 Icon-strip flyouts resize on their free edges and retain sizes (#5713); interim macOS cursor delivery (#2292) uses existing artwork and host-owned AppKit cursors; headless coverage only, native menu/focus/handback and display validation pending. Dock groups collapse to their tabs by a double-click on a tab (UI.8); Preferences › General › Constrain Angle acts for the arrow keys, Shift drags and new objects (#394, 2026-10-21); numeric-field pointer selection and focus regression-tested (#1326, in part; short movements still select all); RPM runtime capabilities and glibc floor checked (#1275; real-distro install/start-up pending), Eyedropper cursor with precise-setting checks (#1269), Preferences, shortcut editor (chords with Shift and a punctuation key fire as typed; other apps' text shortcut sets imported), workspaces (each keeps its layout changes until Reset <name>, UI.7), Window › Help Bar shown or hidden apart from the status bar and kept in saved workspaces, panels docked by dragging into any dock group (as tabs or a top/bottom split) or into the icon column, and closed from a dock tab's context menu (UI.6), a custom title bar on Windows/Linux with a Home button, content-sized dialogs, menus that scroll when longer than the window and macOS native menu dismissal done (M14.8), and native macOS save sheets with a Format menu (#866); titled PDF exports set `DisplayDocTitle` for viewers and accessibility checkers (#3646); accessibility and broader Windows/Linux packaging/QA pending; floating tab groups collapse into the side icon rail and opened rail panels fold back into it (#5925, in part), with pointer and native-window regression coverage; estimates unchanged; numeric spinner arrows keep repeating while held with the mouse (#6307) | 18–28 | | — | Interaction fidelity pass (every tool's modifiers, Properties panel per context, isolation, nuance; width-point creation and adjoining adjustment regression-tested; dialog layout reviewed) | ⬜ (new ruler-guide Alt orientation implemented; existing-guide Escape cancellation regression-tested; broader pass remains) | 60–90 | | — | Hardening at scale (big-file corpus, fuzzing, cross-platform + browser QA) | 🟡 PngSuite integrity and bounded fetching verified (#1729); real-world corpus/manual QA remain | 50–80 | | M14 follow-up | Color Picker layout (#2008) | ✅ Compact controls, centered header, stacked actions, aligned fields and screen sampling; narrow windows scroll vertically | Included above | @@ -193,6 +195,10 @@ separate. Scores and hours unchanged. [Behavior and command details](development | Date | Change | Summary | |---|---|---| +| 2026-11-10 | minor | M10/G5: Game HUD built-in graphic style library; estimates unchanged | +| 2026-11-10 | minor | M10/G5: Map Markers built-in symbol library (Pin, Flag, Crosshair, Checkpoint); estimates unchanged | +| 2026-11-10 | minor | M7: Spelling › Auto Spell Check in the context menu of type (#4936); the dialogs remain; scores and estimates unchanged. | +| 2026-11-10 | minor | M7: right-click suggestions, Ignore All and Add to Dictionary on a word Auto Spell Check underlined (#4936); the dialogs remain; scores and estimates unchanged. | | 2026-11-10 | minor | Current focus: the Effect Gallery's filter thumbnails and in-dialog preview are in (G2). Scores and estimates of other areas unchanged. | | 2026-11-09 | minor | M7: Auto Spell Check (#4936); the dialogs and the right-click Spelling menu remain; scores and estimates unchanged. | | 2026-11-09 | 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. Synthetic evidence: `crates/pdf/src/tests/actual_text.rs`. | diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 2e8b46178b..dfa2a29574 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1,6 +1,8 @@ # Parity with Adobe Illustrator -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-10 · **Change:** minor (right-click on a word Auto Spell Check underlined: its suggestions, Ignore All and Add to Dictionary, #4936; previously minor: Canvas: a 3D effect changed on type or a group redraws where its solid was; Fit to Artwork Bounds and per-artboard SVG export build each solid once for all artboards; previously minor: Effect Gallery: a thumbnail for each filter and a preview area inside the dialog, on an original drawing; Raster effects 52% → 55%, hours 1–2 → none; headline numbers unchanged; Auto Spell Check: `edit.autoSpellCheck` underlines the unknown words, #4936; previously minor: PDF editable import preserves authored ActualText once, including empty/nested spans and authored ordering (#6165); cross-line/style layout remains approximate; scores and estimates unchanged; PDF marked-text export (#6309): compatible glyphs stay on one layout line with per-glyph offsets; scores and estimates unchanged; G5: UI Frames built-in symbol library with default 9-slice; bundled content ~32%; previously minor: G5: dynamic symbol part on-canvas opacity/blend/gradient/pattern; strokes remaining no longer lists Overlap/auto corners; symbols ~88%; previously minor: interim macOS cursor delivery, #2292; native validation pending; scores and estimates unchanged; previously minor: harakat paint fallback clarified; previously minor: current Guides feature-area rows consolidated using existing ruler evidence; scores and estimates unchanged; previously minor: Control bar › Snapping includes the existing Snap to Glyph and Alignment Guides toggles (#6164); scores and estimates unchanged; previously minor: G5 docs: Art brush Overlap and Pattern brush auto corners removed from strokes remaining; symbols remaining lists dynamic on-canvas beyond solid and guides outside the art; previously minor: custom dictionary and Ignore All: `text.spelling.addWord`, `removeWord`, `changeWord`, `dictionary` and `ignoreAll`, #4936; previously minor: EPS import: embedded fonts (composite, Type 42, CID-keyed, Type 1, CFF FontSet) draw their glyphs; spell check engine: `text.spelling.check` and `text.spelling.suggest` on craft-proof, #4936; previously minor: floating tab groups collapse into the side icon rail and opened rail panels fold back into it, #5925 in part; `.ai`/EPS type keeps its tab stops, and right-aligned lines with tabs lay out as the file's page, #6147; `.ai`/EPS type from the text document lays its lines out closer to the file's page, within limits, #6137; `.ai` and EPS import: older Art brush objects read; numeric fields step on wheel hover without taking keyboard focus, and a panel wheel turn cannot seed a canvas zoom glide, #5949; Character Styles panel: a double-click on a style's row opens its Character Style Options; the dialog keeps a fixed width and scrolls its sections, so its buttons stay on screen; Tools stays beside the canvas with left-side panels; new gradients follow document color mode; Selection QoL: marquee modes and visible feedback, #5313; SVG CSS classes survive export and repeated import in all four styling modes (#2480); current-main integration retains event attributes and scripts; #3380 deletion-only review follow-up: independent survivors keep gradient placement, owned subpaths avoid discarded copies, and contracts/status/evidence are clarified; endpoint highlighting remains open; scores and estimates unchanged; the canvas keeps selection outlines and anchors between frames; Indian-language hyphenation review and license allowlist, #4947; Stroke gradients: an arrowhead aligned to the tip is painted to the corners of its base, #5964; Drop Shadow and glow dialogs: spinner arrows, #5367, #5368; Stroke Weight Up and Down shortcuts, #5797; Hindi catalog and contributor loanword preferences; full wording review in progress; Properties in Edit Artboards: a Transform section with the reference point above the Artboards section, #5219; the Control bar's Stroke: and Opacity: links scrub their fields, #4088; an image zoomed in on is separated, colorized or proofed only where it shows (#4155); a document's first frame renders on the render worker, so opening a heavy file no longer freezes the window, #4155; Control bar Paragraph section with type selected, #5372; translating unchanged type reuses its glyph and character-stroke outlines; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x; public release notes through 30.7, August 2026; Units › East Asian Type acts, with Q and Ha units; scores unchanged) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-10 · **Change:** minor (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) + +> **Flyout update:** 2026-11-06 — resizable icon-strip flyouts and bottom-aligned panel footers (#5713); scores and estimates unchanged. ## Feature submission evidence @@ -10,6 +12,8 @@ Numeric fields step on wheel hover without taking keyboard focus (#5949). Arrow Raster rendering fits and preflattens curved stroke outlines more tightly only below four times the raster tolerance, retaining thin-band coverage without changing stroke weight or vector export geometry. Current cached character/object outlines, cropped long strokes, gradient clips and effect rasters share the helper; cropped-region reuse and guarded flattening remain. The unchanged `fractional_curved_strokes_retain_coverage_between_notches` regression covers fractional weights, rotation, phase, opacity and f32-rounded endpoints. This is a quality/cost tradeoff, not a speed claim. Scores and estimates unchanged. +Icon-strip flyouts resize from the canvas-side edge and bottom, keeping the icon-column edge anchored (#5713). Independent group heights and flyout widths persist in workspaces; saved heights override content fitting while untouched heights still fit content. Shared panel button bars stay at the bottom after enlargement. Regressions: `panel_docking::tests::glyphs_and_artboards_flyouts_keep_user_sizes` and `expanded_panel_footers_stay_at_the_bottom_with_short_and_long_lists`. Scores and estimates unchanged. + **PR #3273 revision — 2026-11-04:** Thin curved stroke coverage ported to the current raster-only cache, cropped-long-stroke and effect paths with guarded flattening; vector export geometry unchanged. Scores and estimates unchanged. Group Selection keeps an already selected component selected during a drag; a completed click still adds its next enclosing group. The current Direct Selection click/release machinery is shared, preserving compound-member picks, Shift deselection, isolation and masked-art dragging. Outline Stroke continues to preserve all original fills, including open contours; the change does not remove fills. Regressions: `group_selection_distinguishes_selected_leaf_drags_from_clicks` and `outline_fill_and_stroke_move_independently_with_group_selection` cover tool events, independent component movement and Undo/Redo. Scores and estimates unchanged. @@ -41,7 +45,7 @@ Artboard Options forwards the active Artboard tool's Scale Artwork with Artboard | Date | Change | Summary | |---|---|---| -| 2026-11-10 | minor | Type advanced: right-click suggestions, Ignore All and Add to Dictionary on a word Auto Spell Check underlined, #4936; evidence added; the dialogs remain; scores and hours unchanged. | +| 2026-11-09 | minor | Stroke panel: Line Arrow, a 41st generated arrowhead: two arms of the head's weight (stroke weight × arrowhead scale, at least 0.25 pt: the line's weight at 100 % for lines of 0.25 pt or more) at right angles, a sharp tip and square-cut ends, twice as wide as the other heads; bounds and clicks follow each head's own reach (`stroke.set` `LineArrow`, #5421); scores and estimates unchanged | | 2026-11-09 | minor | Canvas: a 3D effect (Extrude & Bevel, Inflate, Rotate, Revolve) changed on type or a group draws again where its art was and is, measured by that art; the canvas measures through its renderer and draws the part with the art it made to measure it. Exports and Object › Rasterize take the solid of 3D type. Fit to Artwork Bounds and per-artboard SVG export measure every artboard through one renderer, building each solid once. A 3D effect on a fill or stroke that builds nothing (Revolve after Roughen) no longer overflows the stack on the canvas, in Object › Rasterize and in raster and EPS exports: the fill or stroke draws as without it. Tests `tests::changed::a_3d_effect_changed_on_type_or_a_group_changes_where_its_solid_was`, `fx::tests::a_renderer_measures_the_art_on_each_artboard_building_each_solid_once`, `canvas::tests::an_edit_to_a_3d_effect_redraws_with_the_art_measured`, `fx::tests::a_3d_effect_that_builds_nothing_draws_the_item_as_without_it`. Scores and estimates unchanged. | | 2026-11-07 | minor | File formats and Type core (#6147): `.ai`/EPS type keeps its paragraphs' tab stops (positions and alignments; leaders aren't read; at most 1,024 a paragraph and 2^20 a story), and right-aligned area type sets the text after a line's last tab against the right edge, the text before it at its stops; centred and justified lines are aligned as a whole as before; evidence added. Scores and estimates unchanged. | | 2026-11-07 | minor | File formats and Type core (#6137): `.ai`/EPS type from the text document keeps auto leading per line, its hyphenation options, may show more of the last lines the file sets in an area frame of its own, when growing the frame by its lines' deepest descent plus 0.05 pt shows them, and a line a soft return ends is justified; evidence added. Limits: frames grow only for area type of one frame, horizontal, by its lines' deepest descent plus 0.05 pt; type in a font that isn't installed, and hyphenation in a language that isn't imported, still lay out differently. Scores and estimates unchanged. | @@ -59,6 +63,7 @@ Artboard Options forwards the active Artboard tool's Scale Artwork with Artboard | 2026-11-06 | minor | Stroke gradients: an arrowhead whose tip sits on the end of a long straight leg is painted by the gradient to the corners of its base. The slices that reach across a head now run to the end of its reach instead of narrowing towards the next corner (#5964). Test: `stroke::tests_gradient::slices_cover_an_arrowhead_on_a_long_straight_leg`. Scores and estimates unchanged. | | 2026-11-06 | minor | Width profiles: the width between two width points follows a smooth curve instead of a straight line, so a stroke no longer kinks at each width point (#5714). Each side is a monotone cubic through its points: flat at a widest or narrowest point, never past either point of a span; stacked points still step. Straight runs are sampled between width points to the drawing tolerance. Scores and estimates unchanged. | | 2026-11-05 | minor | A nearby hit on a plain long stroke or outline avoids assembling its whole path. A hit near the middle of a 200,000-anchor path took about 11–13 ms before and 1.0–1.4 ms after in paired runs on a busy Windows machine; a miss inside the path's box fell from 18.7 ms to 1.6 ms, while a distant miss was unchanged. Other stroke styles and fill hits keep their existing checks. Scores and estimates unchanged; idle performance budgets remain unverified. | +| 2026-11-06 | minor | Icon-strip flyouts resize on their free edges and retain sizes with workspaces (#5713); saved heights beat auto-fit; panel footers stay at the bottom after enlargement. Scores and estimates unchanged. | | 2026-11-05 | minor | Translating a type object without changing its text or formatting reuses glyph geometry and expanded character-stroke outlines between frames. The text appears at its new position with unchanged pixels. Scaling the type, editing its content or formatting, or changing installed fonts rebuilds the geometry; scores and estimates unchanged. | | 2026-11-05 | minor | Moving a large selection reuses the object locations found during command validation. A 20,000-object nudge took 58.07 ms before and 51.26 ms after in paired median runs; object positions, selection, and undo behavior stay the same. Scores and estimates unchanged. | | 2026-11-05 | minor | Canvas: an image drawn larger than 1,024 pixels at the size it shows, with its colours made again (separated into ink planes, colorized or shown through Separations Preview), has them made only for the 1,024-pixel tiles in view, each kept for later frames (#4155). Zooming in to 50%, 100% and 200% on the file of #4155 went from 8.6–9.0 s to 0.78 s, 0.05 s and 0.05 s (measured, M3 Pro, one run each), with the same pixels. Scores and estimates unchanged. | @@ -214,17 +219,17 @@ dominate; 3D, graphs and automation are specialist). They sum to 105. Feature de | Appearance, transparency, graphic styles, masks | 5 | 97% | raster effect reach in preview bounds | 1–2 | estimated; Transform typing, sliders, preview, and undo are covered in `crates/ui-egui/src/panels/tests_appearance.rs` | | 3D and Materials (and Turntable) | 4 | ~25% | live Revolve with automatic smooth vector shading and default-on continuous circular caps, Extrude & Bevel (twist, taper, caps, five bevel shapes), Inflate and Rotate with Position presets (colored Inflate uses smooth membrane lighting; white-light Inflate retains its existing shading; Extrude & Bevel and Rotate retain planar shading; one to ten colored lights, shared neutral ambient, painter visibility); materials, light presets, shadows, ray tracing, the rest of 3D Classic (Revolve, Rotate, Map Art), Turntable views, textures, map art and shading in 3D export | 30–55 | estimated (Extrude & Bevel, Inflate and Rotate added 2026-10-12) | | Type core | 9 | 80% | Auto-leading style resets are implemented; Hyphenation… and Justification… options are done (#2310, #2755), and a paragraph's Auto Leading also sets the Character panel's Leading, the Alt+↑/↓ leading nudge and Fill with Placeholder Text; remaining: Optical Margin Alignment, Middle Eastern features beyond bidi layout, optional group font-size preservation; transformed character controls fixed (#1034), see [type-parity.md](type-parity.md) | 14–19 | estimated; eleven-language pattern hyphenation in both composers, with grapheme and shaping-cluster protection (#4947, `hyphen::tests` and `layout::wrapping_tests`); Sanskrit patterns pending an allowlisted source; recent-font groups in font pickers (#3515); full-name font matches regression-tested (#1258); mixed paragraph alignment indication implemented; headless regressions, full integration CI and visual review pass; localized legacy family-name fallback with loaded/catalog regressions (#2208); Fractional Widths per type object regression-tested; color emoji fonts with bitmap glyphs (`sbix`, `CBDT`) draw and export; threading ports: every selected area type and type on a path shows its in and out ports (empty, arrow, red "+"), and the Selection tool threads from either, the in port into a frame before it, and a double-click on a threaded port breaks the thread there (`threads::tests::break_splits_the_thread_and_the_story_flows_into_the_first_part`, `select::tests::a_double_click_on_a_threaded_port_breaks_the_thread`, `canvas::tests::a_double_click_on_a_threaded_out_port_breaks_the_thread`) (#2572; `select::tests::a_click_on_the_in_port_threads_into_a_frame_before_it`, `text::tests::selected_type_shows_its_ports_in_each_state`, `threads::tests::add_before_threads_the_story_from_the_new_frame_into_the_clicked_one`, live screenshot); the Glyphs panel highlights and scrolls to the character selected with the Type tool (#4908, `panels::glyphs` tests); the OpenType panel lists only `ss01`–`ss20` sets present in the selected font and uses its custom names when supplied; Type-range desktop Copy publishes styled art and keeps font family, size and color on canvas Paste after editing (#5636); paint-only Arabic harakat keep joining with conditional GDEF-mark ownership and Insert Kashidas base-letter paint (`tests::harakat`) | -| Type advanced (CJK, spelling, Touch Type, Retype) | 4 | 50% | CJK vertical composition (ruby, mojikumi), variable font axes, tab leaders, spell check (engine, custom dictionary and Auto Spell Check with its right-click suggestions done, #4936; the dialogs remain), Touch Type, Retype | 20–28 | estimated; upright fallback for fullwidth `!` / `?` regression-tested; score and hours unchanged | -| Symbols, blends, envelopes, Repeat, perspective | 5 | 88% | remaining: dynamic symbols' `.ai` round trip, further built-in symbol libraries (Basic Shapes and UI Frames with default 9-slice are done), envelope Anti-Alias/Preserve Shape, 9-slice guides outside the art; Symbol Options › Registration, Export Type (Graphic / Movie Clip) and 9-slice guides (drawn and draggable during symbol editing, #5280) and Symbol Type (dynamic on-canvas fill/stroke including gradient/pattern, opacity and blend, #4938) are done | 4–7 | estimated; Blend panel Type and Ramp control step easing with a separate color Shift (#2539); Blend Options retains spacing and orientation; polynomial curves are original approximations; interactive selected mirror axis implemented; bounding-box handles take priority over the axis line (focused regression and native checks passed; full CI blocked by an unrelated text test); #2544 spine Anchor Point conversion and picking regression-tested | -| Type advanced (CJK, spelling, Touch Type, Retype) | 4 | 50% | CJK vertical composition (ruby, mojikumi), tab leaders, spell check (engine, custom dictionary and Auto Spell Check with its right-click suggestions done, #4936; the dialogs remain), Touch Type, Retype | 20–28 | estimated; upright fallback for fullwidth `!` / `?` regression-tested; score and hours unchanged | -| Symbols, blends, envelopes, Repeat, perspective | 5 | 88% | remaining: dynamic symbols' `.ai` round trip, further built-in symbol libraries (Basic Shapes and UI Frames with default 9-slice are done), envelope Anti-Alias/Preserve Shape, 9-slice guides outside the art; Symbol Options › Registration, Export Type (Graphic / Movie Clip) and 9-slice guides (drawn and draggable during symbol editing, #5280) and Symbol Type (dynamic on-canvas fill/stroke including gradient/pattern, opacity and blend, #4938) are done | 4–7 | estimated; Blend panel Type and Ramp control step easing with a separate color Shift (#2539); Blend Options retains spacing and orientation; polynomial curves are original approximations; interactive selected mirror axis implemented; bounding-box handles take priority over the axis line (focused regression and native checks passed; full CI blocked by an unrelated text test); #2544 spine Anchor Point conversion and picking regression-tested | +| Type advanced (CJK, spelling, Touch Type, Retype) | 4 | 50% | CJK vertical composition (ruby, mojikumi), variable font axes, tab leaders, spell check (engine, custom dictionary and Auto Spell Check with its right-click suggestions and Spelling › Auto Spell Check done, #4936; the dialogs remain), Touch Type, Retype | 20–28 | estimated; upright fallback for fullwidth `!` / `?` regression-tested; score and hours unchanged | +| Symbols, blends, envelopes, Repeat, perspective | 5 | 88% | remaining: dynamic symbols' `.ai` round trip, further built-in symbol libraries (Basic Shapes, UI Frames with default 9-slice, and Map Markers are done), envelope Anti-Alias/Preserve Shape, 9-slice guides outside the art; Symbol Options › Registration, Export Type (Graphic / Movie Clip) and 9-slice guides (drawn and draggable during symbol editing, #5280) and Symbol Type (dynamic on-canvas fill/stroke including gradient/pattern, opacity and blend, #4938) are done | 4–7 | estimated; Blend panel Type and Ramp control step easing with a separate color Shift (#2539); Blend Options retains spacing and orientation; polynomial curves are original approximations; interactive selected mirror axis implemented; bounding-box handles take priority over the axis line (focused regression and native checks passed; full CI blocked by an unrelated text test); #2544 spine Anchor Point conversion and picking regression-tested | +| Type advanced (CJK, spelling, Touch Type, Retype) | 4 | 50% | CJK vertical composition (ruby, mojikumi), tab leaders, spell check (engine, custom dictionary and Auto Spell Check with its right-click suggestions and Spelling › Auto Spell Check done, #4936; the dialogs remain), Touch Type, Retype | 20–28 | estimated; upright fallback for fullwidth `!` / `?` regression-tested; score and hours unchanged | +| Symbols, blends, envelopes, Repeat, perspective | 5 | 88% | remaining: dynamic symbols' `.ai` round trip, further built-in symbol libraries (Basic Shapes, UI Frames with default 9-slice, and Map Markers are done), envelope Anti-Alias/Preserve Shape, 9-slice guides outside the art; Symbol Options › Registration, Export Type (Graphic / Movie Clip) and 9-slice guides (drawn and draggable during symbol editing, #5280) and Symbol Type (dynamic on-canvas fill/stroke including gradient/pattern, opacity and blend, #4938) are done | 4–7 | estimated; Blend panel Type and Ramp control step easing with a separate color Shift (#2539); Blend Options retains spacing and orientation; polynomial curves are original approximations; interactive selected mirror axis implemented; bounding-box handles take priority over the axis line (focused regression and native checks passed; full CI blocked by an unrelated text test); #2544 spine Anchor Point conversion and picking regression-tested | | Image Trace, graphs, image tools | 3 | 75% | graph Column designs, Image Trace Create Strokes depth (Create Object Mosaic is done; junction-returning piece survival has source-generated regressions in `image-trace-quality.md`; simpler contour walk, identical output; an edge's sub-pixel shift is the same from either side; notches read only their own piece; collapsed loops keep few segments, so Paths is monotone on the code-drawn sweep) | 5–8 | estimated (raised from 72%); quick presets reveal adjustment controls, Properties reopens them; Live trace result bounds and selection highlights exclude the retained bitmap except in source-image views (scores/hours unchanged) | | Live vector effects | 5 | 85% | Outline Object, SVG Filters | 4–8 | measured count 49/50 (Pathfinder 13/13 with Trap), depth estimated; Warp Options controls verified by focused checks and original-image review | | 3D and Materials (and Turntable) | 4 | ~25% | live Revolve with automatic smooth vector shading and default-on continuous circular caps, Extrude & Bevel (twist, taper, caps, five bevel shapes), Inflate and Rotate with Position presets (colored Inflate uses smooth membrane lighting; white-light Inflate retains its existing shading; Extrude & Bevel and Rotate retain planar shading; one to ten colored lights, shared neutral ambient, original lighting presets, painter visibility); materials, shadows, ray tracing, the rest of 3D Classic (Revolve, Rotate, Map Art), Turntable views, textures, map art and shading in 3D export | 30–55 | estimated (Extrude & Bevel, Inflate and Rotate added 2026-10-12) | -| Type advanced (CJK, spelling, Touch Type, Retype) | 4 | 50% | CJK vertical composition (mojikumi), variable font axes, tab leaders, spell check (engine, custom dictionary and Auto Spell Check with its right-click suggestions done, #4936; the dialogs remain), Touch Type, Retype | 20–28 | estimated; No Break keeps marked characters on one line; upright fallback for fullwidth `!` / `?` regression-tested; score and hours unchanged | -| Type advanced (CJK, spelling, Touch Type, Retype) | 4 | 50% | CJK vertical composition (mojikumi), tab leaders, spell check (engine, custom dictionary and Auto Spell Check with its right-click suggestions done, #4936; the dialogs remain), Touch Type, Retype | 20–28 | estimated; No Break keeps marked characters on one line; upright fallback for fullwidth `!` / `?` regression-tested; score and hours unchanged | +| Type advanced (CJK, spelling, Touch Type, Retype) | 4 | 50% | CJK vertical composition (mojikumi), variable font axes, tab leaders, spell check (engine, custom dictionary and Auto Spell Check with its right-click suggestions and Spelling › Auto Spell Check done, #4936; the dialogs remain), Touch Type, Retype | 20–28 | estimated; No Break keeps marked characters on one line; upright fallback for fullwidth `!` / `?` regression-tested; score and hours unchanged | +| Type advanced (CJK, spelling, Touch Type, Retype) | 4 | 50% | CJK vertical composition (mojikumi), tab leaders, spell check (engine, custom dictionary and Auto Spell Check with its right-click suggestions and Spelling › Auto Spell Check done, #4936; the dialogs remain), Touch Type, Retype | 20–28 | estimated; No Break keeps marked characters on one line; upright fallback for fullwidth `!` / `?` regression-tested; score and hours unchanged | | Raster effects (Effect Gallery) | 4 | 55% | — | — | estimated (raised from 52%: the Effect Gallery's filter thumbnails and in-dialog preview, an original landscape drawing passed through each filter, [Filter Gallery overview](https://helpx.adobe.com/photoshop/desktop/effects-filters/get-started-with-filters/filter-gallery.html), `dialogs::effect_gallery::tests::gallery_shows_thumbnails_and_an_in_dialog_preview`; the gallery itself shipped in #2883, six categories, per-filter settings, ordered stack, live canvas preview, one undo step, `stack_ok_is_one_undo_step`, `stack_preview_is_one_interaction`); measured count 57/57 (Artistic complete with Colored Pencil, Fresco, Paint Daubs, Palette Knife, Rough Pastels and Underpainting; Sketch complete with Torn Edges and Conté Crayon, `pixel::tests_sketch::conte_crayon_*`); texture redraw distances optimized (#1257), pixels verified; the score stays under 100% because the filters are original approximations; depth estimated | -| Symbols, blends, envelopes, Repeat, perspective | 5 | 88% | remaining: dynamic symbols' `.ai` round trip, further built-in symbol libraries (Basic Shapes and UI Frames with default 9-slice are done), envelope Anti-Alias/Preserve Shape, 9-slice guides outside the art; Symbol Options › Registration, Export Type and Symbol Type (dynamic on-canvas fill/stroke including gradient/pattern, opacity and blend, #4938) and on-canvas 9-slice guides (#5280) are done | 4–7 | estimated | +| Symbols, blends, envelopes, Repeat, perspective | 5 | 88% | remaining: dynamic symbols' `.ai` round trip, further built-in symbol libraries (Basic Shapes, UI Frames with default 9-slice, and Map Markers are done), envelope Anti-Alias/Preserve Shape, 9-slice guides outside the art; Symbol Options › Registration, Export Type and Symbol Type (dynamic on-canvas fill/stroke including gradient/pattern, opacity and blend, #4938) and on-canvas 9-slice guides (#5280) are done | 4–7 | estimated | | Image Trace, graphs, image tools | 3 | 75% | graph Column designs, Image Trace Create Strokes depth (Create Object Mosaic is done; junction-returning piece survival has source-generated regressions in `image-trace-quality.md`; large images trace with a warning; Auto Color keeps rare distinct colours) | 5–8 | estimated (raised from 72%); quick presets reveal adjustment controls, Properties reopens them | | Layers, artboards, document setup | 5 | 78% | Selected-artboard deletion is consistent across panel actions (all-selected retains artboard 1); history prunes removed indices while preserving valid multiselection; remaining: 30.0's artboard locking and colours and managing artboards from the canvas, Layers panel row context menus and Collect for Export (click-to-fit objects is done, #1227) | 5–8 | estimated (lowered from 82%: target moved); Artboard deletion keys keep artwork and the first of an all-selected set; Artboard Options' Show Center Mark and Show Cross Hairs draw on the canvas only (exports and print leave them out), regression-tested; Artboard Options' Show Video Safe Areas and Video Ruler Pixel Aspect Ratio (per artboard, native format) are done ([video display options](#evidence-what-ships-today-by-area)), score unchanged | | View & navigation | 3 | 70% | multiple windows and the rest of Arrange (Cascade, Float in Window, Float All in Windows) | 9–14 | estimated; Window › Arrange › Tile and Consolidate All Windows done (score/hours unchanged); document-tab artwork hover/copy and lossless transfer tested (2026-10-22; score/hours unchanged); cached canvas reprojection preserves scale during resize, rotation and DPI changes (regression and contributor original-file evidence below; scores/hours unchanged); cached canvas dimensions match the renderer limit before cache-key creation, view construction and worker submission (regression evidence below) | @@ -237,7 +242,7 @@ dominate; 3D, graphs and automation are specialist). They sum to 105. Feature de | Export for Screens, Asset Export, slices, Save for Web | 3 | 85% | anti-aliasing ghost borders (#983); TIFF choices and settings are implemented | 2–4 | estimated | | Print, colour management, separations, flattener | 3 | 80% | print preview fidelity | 2–4 | estimated | | Automation (Actions, Variables, scripting, batch) | 3 | 60% | a scripting surface (Illustrator: JavaScript/ExtendScript), Batch, image and graph variables, dataset import/export | 8–14 | estimated; MCP `add_text` exposes existing vertical type; score and hours unchanged | -| UI chrome (panels, Properties, workspaces, preferences) | 6 | 80% | Properties per context, 3 Preferences options stored but unused (#394, audited 2026-10-30: Open Documents As Tabs, Scratch Disks, legacy vector clipboard), SVG Interactivity, context menus beyond the canvas, accessibility | 13–20 | estimated; floating panels in OS windows of their own on the desktop (#4135), score and hours unchanged; macOS save Format menu implemented (#866), score and hours unchanged; Eyedropper cursor and precise setting checked (#1269), OS visual QA unverified; numeric-field focus and normal text drags regression-tested (#1326, in part); movements below the click threshold still select all; artboard navigation synchronizes the tool selection before destructive actions; status messages and readouts use stable responsive allocations sized for localized labels and ordinary coordinates (sample widths cached by language/unit/DPI; regression and contributor original-file evidence below; scores/hours unchanged); effect dialogs' colour fields show a swatch that opens the Color Picker (#5365), score and hours unchanged; floating tab groups collapse into the side icon rail and opened rail panels fold back into it (#5925, in part), scores and hours unchanged ; interim macOS cursor delivery (#2292), headless coverage only; native validation pending, score and hours unchanged | +| UI chrome (panels, Properties, workspaces, preferences) | 6 | 80% | Properties per context, 3 Preferences options stored but unused (#394, audited 2026-10-30: Open Documents As Tabs, Scratch Disks, legacy vector clipboard), SVG Interactivity, context menus beyond the canvas, accessibility | 13–20 | estimated; floating panels in OS windows of their own on the desktop (#4135), score and hours unchanged; macOS save Format menu implemented (#866), score and hours unchanged; Eyedropper cursor and precise setting checked (#1269), OS visual QA unverified; numeric-field focus and normal text drags regression-tested (#1326, in part); movements below the click threshold still select all; artboard navigation synchronizes the tool selection before destructive actions; status messages and readouts use stable responsive allocations sized for localized labels and ordinary coordinates (sample widths cached by language/unit/DPI; regression and contributor original-file evidence below; scores/hours unchanged); effect dialogs' colour fields show a swatch that opens the Color Picker (#5365), score and hours unchanged; icon-strip flyouts retain user sizes (#5713); floating tab groups collapse into the side icon rail and opened rail panels fold back into it (#5925, in part), scores and hours unchanged ; interim macOS cursor delivery (#2292), headless coverage only; native validation pending, score and hours unchanged | | Libraries, Links, Package | 2 | 82% | shared libraries, linked graphics, gradients and patterns as library items (no cloud by design) | 2–3 | estimated | | Generative AI (Text to Vector, Generative Recolor, Shape Fill, Concept to Vector, Prompt to Edit, Rewrite Text) | 2 | 0% | a pluggable provider and the panels; needs an owner decision on models | 30–60 | measured (absent) | | **Feature depth** | **105** | **~75%** | | **~250–420** | | @@ -483,12 +488,12 @@ about 1–1.5 agent-hours each, so the other rows (estimated on the older scale) | Appearance, transparency, graphic styles, masks | 5 | 98% | raster effect reach in preview bounds (flattener presets apply in PDF, EPS and print) | 1–2 | | Live vector effects | 5 | 85% | Outline Object, Pathfinder Hard/Soft Mix and Trap (since done: #3061, #3063, #3785), SVG Filters, Transform Patterns and Scale Strokes & Effects on a fill's or stroke's own Transform effect | 6–10 | | 3D and Materials | 4 | ~25% | Initial Revolve, Extrude & Bevel, Inflate and Rotate, with simple lighting; materials, light presets, shadows, ray tracing, Revolve (Classic), Rotate (Classic), Map Art and more complete visibility remain | 25–45 | -| Type advanced | 4 | 50% | CJK composition for vertical type (ruby, mojikumi beyond Line-end Punctuation Half Width — the other sets (and their paragraph-start bracket and indent rules), custom kinsoku sets (beyond Hard, Soft and None) and the Mojikumi Settings dialog —, manual tate-chu-yoko), tab leaders, spell check (its engine, custom dictionary commands and Auto Spell Check are done, #4936: the Check Spelling and Edit Custom Dictionary dialogs remain; a right-click on an underlined word offers its suggestions, Ignore All and Add to Dictionary), Touch Type, Retype; vertical point/area/path type and Type Orientation have initial support (beyond parity, not scored: inline symbols in text) | 20–28 | +| Type advanced | 4 | 50% | CJK composition for vertical type (ruby, mojikumi beyond Line-end Punctuation Half Width — the other sets (and their paragraph-start bracket and indent rules), custom kinsoku sets (beyond Hard, Soft and None) and the Mojikumi Settings dialog —, manual tate-chu-yoko), tab leaders, spell check (its engine, custom dictionary commands and Auto Spell Check are done, #4936: the Check Spelling and Edit Custom Dictionary dialogs remain; a right-click on an underlined word offers its suggestions, Ignore All and Add to Dictionary, and a right-click on type has Spelling › Auto Spell Check), Touch Type, Retype; vertical point/area/path type and Type Orientation have initial support (beyond parity, not scored: inline symbols in text) | 20–28 | | Raster effects (Effect Gallery, Document Raster Effects Settings) | 4 | 35% | ~36 Photoshop-style filters (Artistic, Brush Strokes, Sketch, Stylize) and Texturizer's Load Texture (since done, see the area table above, as is the Effect Gallery, #2883); Document Raster Effects Settings, raster effects in PDF, the pixel-filter pipeline, Radial Blur, Smart Blur (Normal, Edge Only and Overlay Edge), Unsharp Mask, Glowing Edges, Distort (Diffuse Glow, Glass, Ocean Ripple), Pixelate (Color Halftone, Crystallize, Mezzotint, Pointillize), Texture (Craquelure, Grain, Mosaic Tiles, Patchwork, Stained Glass, Texturizer) and Video (De-Interlace, NTSC Colors) are done | 8–14 | | 3D and Materials | 4 | ~25% | Initial Revolve, Extrude & Bevel, Inflate and Rotate, with simple lighting and four original lighting presets; materials, shadows, ray tracing, Revolve (Classic), Rotate (Classic), Map Art and more complete visibility remain | 25–45 | -| Type advanced | 4 | 50% | CJK composition for vertical type (mojikumi beyond Line-end Punctuation Half Width — the other sets (and their paragraph-start bracket and indent rules), custom kinsoku sets (beyond Hard, Soft and None) and the Mojikumi Settings dialog —, manual tate-chu-yoko is done, its up/down settings remain; No Break is done), tab leaders, spell check (its engine, custom dictionary commands and Auto Spell Check are done, #4936: the Check Spelling and Edit Custom Dictionary dialogs remain; a right-click on an underlined word offers its suggestions, Ignore All and Add to Dictionary), Touch Type, Retype; vertical point/area/path type and Type Orientation have initial support (beyond parity, not scored: inline symbols in text) | 20–28 | +| Type advanced | 4 | 50% | CJK composition for vertical type (mojikumi beyond Line-end Punctuation Half Width — the other sets (and their paragraph-start bracket and indent rules), custom kinsoku sets (beyond Hard, Soft and None) and the Mojikumi Settings dialog —, manual tate-chu-yoko is done, its up/down settings remain; No Break is done), tab leaders, spell check (its engine, custom dictionary commands and Auto Spell Check are done, #4936: the Check Spelling and Edit Custom Dictionary dialogs remain; a right-click on an underlined word offers its suggestions, Ignore All and Add to Dictionary, and a right-click on type has Spelling › Auto Spell Check), Touch Type, Retype; vertical point/area/path type and Type Orientation have initial support (beyond parity, not scored: inline symbols in text) | 20–28 | | Type core | 9 | 80% | Middle Eastern features beyond bidi layout, Paragraph Direction, digit types and Kashidas (the Middle Eastern composers, editable bidirectional SVG text, a split caret where directions meet); paint-only harakat keep joining with conditional GDEF-mark colour ownership, but fonts without GDEF mark classes and some AAT/`morx` ligatures can still leave marks painted as their letters; Every-line Composer fidelity for justified and ragged text (available per object; mixed type sizes in a paragraph still break single-line in non-rectangular area type and with text wrap), Optical Margin Alignment, paragraph spacing limit for vertically justified area type, hidden characters, paragraph attributes in the Type tool's copy and paste (the characters keep their styles, the paragraphs take the destination's), mixed-value display in the Paragraph panel for a selection across differing paragraphs, partial selection of type-area anchors by marquee, optional font-size preservation during group scaling (scaled character controls fixed in #1034). Hyphenation and Justification options, Fractional Widths, System Layout, styled Type-range canvas Paste (#5636), and pattern hyphenation for eleven Indian languages with grapheme/cluster protection (#4947) are done; Sanskrit automatic patterns remain pending an allowlisted source | 14–19 | -| Symbols, blends, envelopes, Repeat, perspective | 5 | 90% | further built-in symbol libraries (Basic Shapes and UI Frames with default 9-slice are done), dynamic symbols' `.ai` round trip, envelope Anti-Alias/Preserve Shape output and warp point editing, brush interpolation in blends (M8 fidelity pass done); Symbol Options › Registration and Export Type and on-canvas dynamic part paint (gradient/pattern, opacity, blend) are done; symbol editing shows draggable 9-slice guides (#5280), while guides outside the artwork remain unsupported | 4–7 | +| Symbols, blends, envelopes, Repeat, perspective | 5 | 90% | further built-in symbol libraries (Basic Shapes, UI Frames with default 9-slice, and Map Markers are done), dynamic symbols' `.ai` round trip, envelope Anti-Alias/Preserve Shape output and warp point editing, brush interpolation in blends (M8 fidelity pass done); Symbol Options › Registration and Export Type and on-canvas dynamic part paint (gradient/pattern, opacity, blend) are done; symbol editing shows draggable 9-slice guides (#5280), while guides outside the artwork remain unsupported | 4–7 | | Image Trace, graphs, image tools | 3 | 72% | graph Column designs (Graph Design, Marker designs and series colours set with Group Selection are done), Create Object Mosaic, per-feature stroke/fill choice and varying widths in Image Trace's Create Strokes (Vector Halftone and the Image Trace View modes, Palette and Create Strokes are done) | 6–10 | | Layers, artboards, document setup | 5 | 82% | Layers panel: a confirmation before deleting layers that hold art, Collect for Export, row context menus, the Layer Options dialog for several rows with mixed values, Paste Remembers Layers for sublayers, drag-scrolling a long panel while dragging rows; artboard preset polish (artboard escape routing and document setup modal handoff done; Move Artwork for artboard X/Y edits, Rearrange All Artboards, Document Setup, New Document and the rest of the Layers panel are done) | 4–7 | | View & navigation | 3 | 70% | New View/Edit Views, multiple windows/arrange, Snap to Pixel/Glyph (print tiling is done) | 9–14 | @@ -531,7 +536,7 @@ since 2026-10-01. | **Interaction fidelity:** modifiers, cursors, small behaviours | ~30–40% | The dedicated pass hasn't started, and there has been no side-by-side session with Illustrator yet. A power user notices this first | | **Look & feel** | ~75–80% | Measured against Illustrator 2026 screenshots (2026-10-02); the panels added since haven't been re-measured | | **File interop** | ~85% | SVG/SVGZ, PDF and PDF-compatible `.ai` (and legacy version 7 `.ai` out, keeping layers, groups and type as text), EPS, DXF, EMF/WMF, raster formats, PSD export and PSD/PSB placement (merged image), Place and Links, Package, Print, clipboard flavours. Affinity documents (Affinity 1–3) open natively as editable art, checked against 51 pinned public files (33 current `.af`), with selected saved-thumbnail comparisons and every-board native/SVG/PDF/PSD checks for current files; Affinity export is missing and effects, adjustments and brushes don't import. Affinity isn't an Illustrator feature, so this doesn't raise the parity score. The editing copy inside an Illustrator EPS or `.ai` is read for its structure: layers, groups, names, hidden objects and type, colours, gradients, transparency, images and every artboard (see Out of scope for what it doesn't read yet); DWG has no open spec | -| **Bundled content:** brush, symbol, style and swatch libraries | ~32% | Ours are original and generated in code, and far fewer than Illustrator ships; symbol libraries have two (Basic Shapes, UI Frames with default 9-slice) and brush libraries four (Art Ribbons, Calligraphic Nibs, Pattern Borders, Scatter Shapes) beside User Defined and Other Library… | +| **Bundled content:** brush, symbol, style and swatch libraries | ~36% | Ours are original and generated in code, and far fewer than Illustrator ships; symbol libraries have three (Basic Shapes, UI Frames with default 9-slice, Map Markers), graphic style libraries seven (including Game HUD) and brush libraries four (Art Ribbons, Calligraphic Nibs, Pattern Borders, Scatter Shapes) beside User Defined and Other Library… | | **Performance** | unverified | Multithreaded, off-thread rendering and caches are in place. The last budget run (2026-10-01, loaded machine) measured 290 ms for a 50k-path fit against a 16 ms budget. Re-run `vectorcraft-cli perf` on an idle machine | | **Robustness** | good, new | ~2,840 tests, property tests, no panics in shipped code (lints, the `guard` safety net, import fuzzing), Data Recovery. Missing: a corpus of real-world files, Windows/Linux/browser QA | | **Platforms and 1.0 polish** | ~60% | The macOS app and the web build work, and Finder opens every readable format with the macOS app (#295, #354); on macOS the menus are in the system menu bar, laid out as a Mac app's, with the in-window menus as a fallback (`--in-window-menus`; verified on Windows and by cross-compilation, not yet by hand on a Mac); hybrid-graphics laptops render on the power-saving GPU by default on Windows and macOS (#306), and Windows starts on Direct3D 12, falling back to OpenGL, and loads no Vulkan driver unless `WGPU_BACKEND` asks for it (#545: Vulkan flickered black on an Intel GPU, DX12 and OpenGL didn't; #806: a faulty Vulkan driver crashed the app before its window appeared; verified by unit tests and the reporter's runs with `WGPU_BACKEND`), and Linux on the GPU the desktop runs on, since a Wayland compositor may refuse frames from the other one; a window that fails on its GPU while starting up starts again on the next one instead of crashing (#502; the dual-GPU Wayland case is verified by unit tests and cross-compilation, not on such hardware); web drops land in the document they were dropped on (#359); desktop drops carry no pointer position (winit 0.30), so a dropped document opens as a tab of its own and a picture or text is placed in the middle of the view, while the web places anything dropped on the canvas and opens what is dropped off it, as Illustrator does (#472); a web page that loses its WebGPU device or WebGL context restarts its graphics with the same documents (#369); on Linux/Wayland the clipboard reads the compositor's own (data-control) and copied image files paste, but files can't be dropped on the window under native Wayland until eframe moves to winit 0.31 (#398; the Wayland side is verified by compilation only), so Preferences › Performance › Linux Display Server › X11 (XWayland) opens the window through XWayland, where drops work (#1151; verified by unit tests and cross-compilation, not on a Wayland desktop); on Linux the Paste menu checks the system clipboard on a background thread, so a clipboard owner that never answers no longer freezes the window, while Windows and macOS keep their quick in-line check (#510; the X11 hang verified by the contributor, here by headless tests); on KDE Plasma 6.3+ under Wayland, pens and pen displays reach the app only under XWayland (`WAYLAND_DISPLAY=`) or with KWin's `KWIN_WAYLAND_EMULATE_TABLET=1`, since winit 0.30 has no Wayland tablet input (#491, not verified on hardware); Windows/Linux packaging and accessibility are pending | @@ -713,6 +718,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - Variables: a type object holds one text variable. `variable.bind` and Make Text Dynamic refuse a second one and name the text variable the object has; a visibility variable can still share the object, and a document saved with two text variables on one object opens with both. - Synthetic input validates complete gestures before queue mutation: at most 256 drag steps, 16 clicks and 1,024 pending events; up to 64 control requests per frame, with later requests retained for the next frame (#1709). - The control server writes each reply through a 64 KiB buffer. On Windows 11 it sends the 17 MB `document.inspect` reply of a document with 50,000 objects on one layer to a client over loopback in 0.09 s instead of 34 s. + - Scripts: File › Scripts › Other Script… and `script.run` run a JavaScript file against the open documents as one transaction with one undo step for each changed document. A failed or stopped run puts every document back. `crates/engine/src/tests/script_run.rs`. - Parameter keys: the engine refuses a key that a command's params description doesn't name before the command runs, in every build and for every caller, including the app's own calls, the commands a command runs and the steps of `command.batch` and `action.batch`. An action recorded by an older version still plays from the Actions panel and the Batch dialog (`Session::replay`). `crates/engine/tests/it/param_keys.rs`. - MCP server with 25 tools (drawing, text, effects, Pathfinder, transforms, graphs, text wrap, export, screenshots, any command), attached to the running app or headless. Tool descriptions and replies agree with the engine: format lists come from its format table, `save_file` says it keeps the document's own format, `inspect_document` reports the paint type's characters show, and selection exports report the encoder's warnings. `--automation-read-root` / `--automation-write-root` (on `vectorcraft-cli mcp` and on `vectorcraft --control`) confine the files commands read and write to chosen folders, links followed, with the flags PhotoCraft takes (#832); each flag may be given more than once, a path inside any of its folders being allowed (#3546, `file_access::tests::several_roots_of_a_kind_each_grant_their_access`, `cli::mcp_automation_roots_take_several_folders`). A long export can be cancelled (`notifications/cancelled` stops it at the next page or group and writes nothing), reports page progress to a client that sent a progress token, and does not make other requests wait: engine-free ones answer at once, the rest are refused as busy after two seconds (#2165, #2171, #2172). - MCP protocol: five prompts (`prompts/list` / `prompts/get`: poster, icon set, recolour, trace-and-style, export set), `completion/complete` for prompt arguments and template variables read from the live catalogues (formats, effect ids, command ids, trace presets, swatch and object ids), four resource templates (`vectorcraft://object/{id}`, `//command/{id}`, `//effect/{id}`, `//swatch/{name}`) so an agent reads one thing instead of the whole document, and `logging/setLevel` with `notifications/message`. `window.panel` ids are case-insensitive (display labels work too), `vectorcraft://object/{id}` reads through `document.node {summary: true}` (the same reply bytes from one lookup instead of summarizing the whole document: a leaf read on a 2,000-object document drops from ~20 ms to ~0.06 ms), large containers slice with `document.node {depth?, childLimit?}` (truncated levels report `childCount`), `document.inspect` and the `inspect_document` tool slice the same way so a depth-0 read is the layer skeleton (~9.7 KB instead of ~2 MB on a 2,000-object document), `document.find` locates nodes by name/kind/text with ancestor paths, and the CLI sweeps the protocol surface over stdio against the compiled binary. `docs/mcp.md` has a Protocol section covering the capability table and what is deliberately absent (subscriptions, progress, cancellation, sampling, elicitation, Streamable HTTP — all of which need the transport to interleave reads). @@ -777,7 +783,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - The macOS menu bar is built from the in-window menus (one model, `native_menu`) and laid out as a Mac app's: the VectorCraft menu holds About, Settings ▸ (each Preferences page, General… ⌘K), Language ▸, Appearance ▸ (UI brightness), Services, Hide VectorCraft ⌃⌘H (⌘H stays Hide Edges), Hide Others, Show All and Quit; Window gains Minimize ⌃⌘M, Zoom and Bring All to Front, and Help the system's search field. Its key equivalents go back to egui as key presses, so user shortcuts, focused text fields and the Type tool's input method behave as in the window, and nothing fires twice; enabled, check marks and labels update in place. `--in-window-menus` or `VECTORCRAFT_IN_WINDOW_MENUS=1` keeps the menus in the window; `ui.inspect` reports `nativeMenuBar`. - macOS: Finder opens every format File › Open reads with VectorCraft (double-click, Open With, a drop on the Dock icon, `open -a`), at launch or while it runs; the release and `cargo xtask bundle` apps share one `Info.plist` that declares those document types, owning only VectorCraft's own formats. The DMG opens on a designed Finder window, VectorCraft.app beside the `Applications` link over a background with the app icon (#493). - Swatch and graphic style libraries, Libraries panel files, presets and plug-ins open wherever they are dropped on the window, as File › Open opens them. - - **Symbol libraries** ([public source](https://helpx.adobe.com/illustrator/desktop/manage-objects/traces-mockups-symbols/create-or-import-symbol-libraries.html)): Window › Symbol Libraries and the Symbols panel's Symbol Libraries Menu open each library in a library panel of its own, as swatch and graphic style libraries do. The built-in libraries, Basic Shapes and UI Frames (Panel, Button and Bar with default 9-slice guides), are original art generated in code (`crates/engine/src/cmd/symbollib.rs`). A click on a symbol adds it to the document's Symbols as one undo step, with its Symbol Options (size, registration, export type, 9-slice guides) and every resource it uses (the symbols it nests, patterns, swatches, brushes, graphic styles, images), and makes it the current symbol; a symbol the document already has is not added again and another symbol of the same name keeps its name, the library's comes in numbered. Thumbnails, in the library panels and the Symbols panel, draw a symbol with the symbols it nests and the patterns and images it uses. Dragging a library symbol onto the canvas also places an instance there, in the same step ([placing from a library](https://helpx.adobe.com/illustrator/desktop/manage-objects/traces-mockups-symbols/create-and-place-symbols.html)). Save Symbols (the library menu) and Save Symbol Library… (the Symbols panel menu) write the document's symbols as a `.vectorcraft` document holding only them, into the user library folder (listed under User Defined) or a file; Other Library… reads the symbols of any document VectorCraft opens; a file it can't read is an error and opens no panel. Tests: `crates/engine/src/tests/symbollib.rs`, `crates/ui-egui/src/panels/tests_symbol_libraries.rs`, `panels::symbols::tests::thumbnails_show_the_symbols_a_symbol_nests`, `canvas::tests::a_library_symbol_dropped_on_the_canvas_is_added_and_placed_there_in_one_step`. + - **Symbol libraries** ([public source](https://helpx.adobe.com/illustrator/desktop/manage-objects/traces-mockups-symbols/create-or-import-symbol-libraries.html)): Window › Symbol Libraries and the Symbols panel's Symbol Libraries Menu open each library in a library panel of its own, as swatch and graphic style libraries do. The built-in libraries, Basic Shapes, UI Frames (Panel, Button and Bar with default 9-slice guides) and Map Markers (Pin, Flag, Crosshair and Checkpoint, no default 9-slice), are original art generated in code (`crates/engine/src/cmd/symbollib.rs`). A click on a symbol adds it to the document's Symbols as one undo step, with its Symbol Options (size, registration, export type, 9-slice guides) and every resource it uses (the symbols it nests, patterns, swatches, brushes, graphic styles, images), and makes it the current symbol; a symbol the document already has is not added again and another symbol of the same name keeps its name, the library's comes in numbered. Thumbnails, in the library panels and the Symbols panel, draw a symbol with the symbols it nests and the patterns and images it uses. Dragging a library symbol onto the canvas also places an instance there, in the same step ([placing from a library](https://helpx.adobe.com/illustrator/desktop/manage-objects/traces-mockups-symbols/create-and-place-symbols.html)). Save Symbols (the library menu) and Save Symbol Library… (the Symbols panel menu) write the document's symbols as a `.vectorcraft` document holding only them, into the user library folder (listed under User Defined) or a file; Other Library… reads the symbols of any document VectorCraft opens; a file it can't read is an error and opens no panel. Tests: `crates/engine/src/tests/symbollib.rs`, `crates/ui-egui/src/panels/tests_symbol_libraries.rs`, `panels::symbols::tests::thumbnails_show_the_symbols_a_symbol_nests`, `canvas::tests::a_library_symbol_dropped_on_the_canvas_is_added_and_placed_there_in_one_step`. - **9-slice scaling** ([public source](https://helpx.adobe.com/illustrator/desktop/manage-objects/traces-mockups-symbols/maintain-proportions-while-scaling-symbols.html)): a scaled instance of a symbol with Enable Guides for 9-Slice Scaling on stays an instance and keeps the parts of its art outside the guides at their size. New guides sit a quarter of the symbol's width and height in from each edge ([reference](https://help.adobe.com/archive/en/illustrator/cs6/illustrator_reference.pdf), Use 9-slice scaling section); saved guides keep their values. The rest is VectorCraft's own rule: the corners keep both sizes, the top and bottom edges stretch in width, the left and right edges in height and the center in both; an instance smaller than its two outer cells on an axis shrinks them in proportion and leaves the center empty; the cells are sized along the symbol's axes before the instance's rotation, shear or reflection. A path with solid paint that crosses a guide is cut there and stays one path, its stroke at its weight with Scale Strokes & Effects on or off; type, images, live objects and gradient or pattern paint that cross a guide are drawn in each cell they reach, clipped to it, except those that draw symbol art (a nested instance, type with an inline graphic, a placed document, a brushed stroke, or a pattern whose tile draws one of these), which are placed by the cell their center is in; an object in one cell is placed by that cell and stays as it is. The canvas, bounds, the Eyedropper, Break Link to Symbol and the PDF, EPS, DXF, EMF/WMF and SVG exports place the art the same way; SVG writes such an instance as its placed art instead of a `<use>`, and DXF and WMF, which do not clip, cut every path that crosses a guide and place other such objects by the cell their center is in. Tests: `symbol_nine_slice::tests` in `crates/doc`, `crates/engine/src/tests/symbol_nine_slice.rs`, `a_scaled_nine_slice_instance_keeps_its_corners` (PDF), `a_scaled_nine_slice_instance_is_written_as_the_canvas_draws_it` (SVG), `a_scaled_nine_slice_instance_is_sampled_as_it_is_drawn` (Eyedropper). - **Symbol editing mode** ([Edit symbols](https://helpx.adobe.com/illustrator/desktop/manage-objects/traces-mockups-symbols/edit-symbols.html), [Symbols panel options](https://helpx.adobe.com/illustrator/desktop/manage-objects/traces-mockups-symbols/symbols-panel-options.html)): a double-click on a symbol instance, the Control bar's Edit Symbol button, a double-click on a symbol in the Symbols panel and the panel menu's Edit Symbol (`symbol.edit`) open the symbol's art on a temporary isolated layer, where the instance shows it (from the panel: centered on the active artboard, or in the view in a document without artboards), with the rest of the document dimmed. Each edit there changes every instance at once; the instances keep their own transforms and stay linked (Break Link to Symbol still expands one), and a dynamic symbol's instances keep their appearance changes to the objects the art still has. Escape, the isolation bar's back button, the Control bar's Exit Symbol Editing Mode and a double-click outside the art leave the mode (`symbol.exitEditing`); leaving without an edit adds no undo step. Saving leaves the editing layer out. Tests: `crates/engine/src/tests/symboledit.rs`, `select::tests::a_double_click_on_a_symbol_instance_edits_its_symbol`, `panels::symbols::tests::edit_symbol_from_the_panel_centers_the_art_on_the_active_artboard_or_the_view`. - **Dynamic symbol appearance follows what an object draws** (VectorCraft's own rule): `symbol.instance.setAppearance` refuses a fill or stroke for an object of the art that does not draw it (a guide, blend, envelope, Repeat, Intertwine group, gradient mesh or placed document; a nested symbol instance's stroke, and its fill unless a solid color or none, which stains its art; an image's fill or stroke without a Convert to Shape or Outline Object effect) with an error that names the key and the object, and the call changes nothing. Opacity, blend and `null`, which takes a stored change back, are taken for every object. Tests: `crates/engine/src/tests/dynamic_symbols.rs`. @@ -790,7 +796,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Reset Transformation** ([Transform symbols](https://helpx.adobe.com/illustrator/desktop/manage-objects/traces-mockups-symbols/transform-symbols.html), [Symbols panel options](https://helpx.adobe.com/illustrator/desktop/manage-objects/traces-mockups-symbols/symbols-panel-options.html)): the Symbols panel menu's Reset Transformation and the Control bar's Reset, shown while symbol instances are selected, give the selected instances their symbol's own scale again, without rotation or shear, as one undo step (`symbol.instance.resetTransform`); an instance in perspective is left as it is. VectorCraft's own rules: each instance keeps the center of its bounding box in place, reflection is removed too, and the menu item and the button are enabled only while a selected instance would change. Tests: `tests::brushsym::reset_transformation_restores_the_symbols_scale_and_keeps_the_center`, `reset_transformation_keeps_the_center_of_art_away_from_the_origin`, `reset_transformation_ignores_a_stored_size_that_is_not_positive`, `reset_transformation_leaves_unchanged_instances_and_refuses_bad_ids`, `panels::symbols::tests::reset_transformation_is_enabled_for_a_transformed_instance_and_resets_it`. - **Expand of dimensions:** Object › Expand, Expand Appearance, Create Outlines and Outline Stroke turn a dimension whose art they change into a plain group of that art, which stays as it is through later moves, scales and edits of what it measured; undo gives the live dimension back (`crates/engine/tests/it/dimensions.rs`; VectorCraft's own rule; estimated, score unchanged). - **Brush libraries** ([public source](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/apply-and-edit-strokes/create-new-brush-libraries.html), [import](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/apply-and-edit-strokes/import-brushes-from-brush-libraries-or-other-files.html), [Brushes panel](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/apply-and-edit-strokes/brushes-panel-overview.html)): Window › Brush Libraries, the Brushes panel's Brush Libraries Menu and its menu's Open Brush Library open each library in a library panel of its own, as swatch, graphic style and symbol libraries do. The built-in libraries (Art Ribbons, Calligraphic Nibs, Pattern Borders, Scatter Shapes) are original brushes generated in code (`crates/engine/src/cmd/brushlib.rs`); Striped Ribbon's art is filled with the library's own pattern and Sparkles scatters the library's own symbol. A click on a brush adds it to the document's Brushes as one undo step with every resource its art uses (patterns, symbols, swatches, graphic styles, images), makes it the current brush and, with paths selected, applies it to them in the same step; a brush the document already has is not added again and a different brush of the same name comes in numbered ("Wave 2"). Shift/Cmd-clicks select brushes for Add to Brushes; a brush dragged onto a path is added and applied to it, and one dragged onto the Brushes panel is added. Save Brushes… / the Brushes panel's Save Brush Library… write the document's brushes (or the selected ones) as a `.vectorcraft` library into the `Brushes` folder next to the preferences, listed under User Defined, or to a file; Other Library… reads the brushes of any document VectorCraft opens. Thumbnails, in the library panels, the Brushes panel and Brush Options, render brush art with the patterns and symbols it uses. Copying brushed art now carries the patterns and symbols its brush's art uses too. Tests: `crates/engine/src/tests/brushlib.rs`, `crates/ui-egui/src/panels/tests_brush_libraries.rs`, `panels::brushes::tests::library_brush_previews_show_the_patterns_their_art_uses`, `canvas::tests::a_library_brush_dropped_on_a_path_is_added_and_applied_in_one_step`. - - A canvas context menu: right-click selects the object under the pointer and lists what applies to the selection (Undo/Redo, clipboard, group, isolation, join, Remove Anchor Points when anchors are selected, masks, compound paths, guides, Transform, Arrange, Select, Export Selection), or the view commands on empty canvas. + - A canvas context menu: right-click selects the object under the pointer and lists what applies to the selection (Undo/Redo, clipboard, group, isolation, join, Remove Anchor Points when anchors are selected, masks, compound paths, guides, Transform, Arrange, Select, Export Selection, and on type Bullets and Numbering and Spelling › Auto Spell Check, checked while it is on), or the view commands on empty canvas. - A right-click over locked objects adds an Unlock submenu to the canvas context menu. The submenu lists up to 20 locked objects under the pointer, topmost first, by the name the Layers panel shows, and choosing one unlocks it (`layer.setProps`). A locked group is listed as one item. Objects on hidden, locked or template layers are not listed. - Native macOS save sheets offer a localised Format menu (#866), built from the request's existing format filters. It selects the suggested filename's format and updates the suffix when changed, including legacy `.drawcraft` names. `apps/vectorcraft/src/mac_save_format.rs` has filename regressions; an actual native SVG save, selection of PDF and cancellation without changing the saved document were verified. - Save / Don't Save / Cancel before closing or quitting with unsaved documents (tabs, Close, Close All, Quit, window close). @@ -1006,7 +1012,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Artboard click-to-fit (#1227):** a plain click fits the topmost editable object or group to a new artboard, including its stroke like Fit to Selected Art, and makes the new artboard active. Art and its selection stay unchanged; creation is one undo step. Handles, modified clicks, drags, Escape and tool changes retain their meaning. Tested inside an artboard and on the pasteboard (`crates/engine/tests/it/artboard_click.rs`); the public [CS6 Printing Guide](https://helpx.adobe.com/content/dam/help/en/indesign/pdf/CS6_PrintGuide.pdf) documents the object-click gesture. This legacy gesture adds evidence without regrading the 2026 canvas controls. - **Rotated views:** with the view rotated, Fit Artboard in Window, Fit All in Window and the status bar's artboard navigator fit the artboard or the art as the view turns it, and a Zoom tool marquee (Animated Zoom or GPU Performance off) zooms to the area dragged across. Ruler guides on no artboard turn with the view. The canvas draws the selection marquee where the tools select, Show Hidden Characters draws the marks of type partly inside the canvas, the Contextual Task Bar stays under the selection, and the Navigator's red box outlines what the window shows. - **Navigator panel options:** the Navigator panel menu's Panel Options… sets the color the view box is drawn in, from a preset list (VectorCraft's own: Light Red, the default, then the layer colors) or a custom color, and Draw Dashed Lines as Solid Lines, off by default, which draws dashed strokes without their dashes in the panel's thumbnail only (`ui.navigatorPanelOptions`; kept with the UI state; behavior reference: [View artwork](https://helpx.adobe.com/illustrator/using/viewing-artwork.html)). -- **Views:** the status bar's artboard navigator (first, previous, next, last; `view.goToArtboard`) goes to an artboard, fits it and synchronizes the Artboard tool selection when that tool is active; ordinary object selection is preserved. Its four buttons are also commands of their own (`view.firstArtboard`, `view.previousArtboard`, `view.nextArtboard`, `view.lastArtboard`), listed in Edit › Keyboard Shortcuts without a default key, so a user can give them keys such as Page Up and Page Down (#5218). Actual Next-button regressions cover keyboard/Properties deletion and Undo in `chrome.rs`. Fit Artboard in Window and Actual Size show the navigator's artboard. The Artboards panel highlights that active artboard: clicking a row makes it active (the Artboard tool's too, while it is chosen) as does clicking an artboard with the Artboard tool, double-clicking its number also fits it in the window and double-clicking its name renames it. Duplicate Artboards, or a row dragged onto New Artboard, copies the artboard with its art (#446). Escape leaves Presentation Mode, `view.screenMode` from it goes back to Normal Screen Mode, and the screen mode isn't saved with the preferences: the app always starts in Normal Screen Mode with its menus and panels (#472). View › Pixel Preview shows the art as the document pixels it rasterizes to, one per point and hard-edged when magnified, turning with a rotated view (it used to draw the smooth vectors, with only the pixel grid over them). In Outline view a template layer keeps drawing in Preview, dimmed, so a picture placed to be traced stays visible under the outlines (#1505, fixes #1486). +- **Views:** the status bar's artboard navigator (first, previous, next, last; `view.goToArtboard`) goes to an artboard, fits it and synchronizes the Artboard tool selection when that tool is active; ordinary object selection is preserved. Its four buttons are also commands of their own (`view.firstArtboard`, `view.previousArtboard`, `view.nextArtboard`, `view.lastArtboard`), listed in Edit › Keyboard Shortcuts without a default key, so a user can give them keys such as Page Up and Page Down (#5218). Actual Next-button regressions cover keyboard/Properties deletion and Undo in `chrome.rs`. Fit Artboard in Window and Actual Size show the navigator's artboard. The Artboards panel highlights that active artboard: clicking a row makes it active (the Artboard tool's too, while it is chosen) as does clicking an artboard with the Artboard tool, double-clicking its number also fits it in the window and double-clicking its name renames it. Duplicate Artboards, or a row dragged onto New Artboard, copies the artboard with its art (#446). Escape leaves Presentation Mode, `view.screenMode` from it goes back to Normal Screen Mode, and the screen mode isn't saved with the preferences: the app always starts in Normal Screen Mode with its menus and panels (#472). View › Pixel Preview shows the art as the document pixels it rasterizes to, one per point and hard-edged when magnified, turning with a rotated view (it used to draw the smooth vectors, with only the pixel grid over them). In Outline view a template layer keeps drawing in Preview, dimmed, so a picture placed to be traced stays visible under the outlines (#1505, fixes #1486). Outline view draws on a white canvas in every interface brightness and Canvas Color, pasteboard included, with the artboards as their edges and no paper (VectorCraft's own rule), so the black outlines of art on the pasteboard show. In Presentation Mode, → and ← go to the next and the previous artboard, and a click anywhere goes to the next one, as the status bar navigator's Next and Previous do (`view.goToArtboard`): on the last artboard → and a click leave the view as it is, and so does ← on the first. The arrow keys do not move the selection there, and the tool does not receive a click, so a click selects and draws nothing (behavior reference: [View artwork](https://helpx.adobe.com/illustrator/using/viewing-artwork.html)). Full Screen Mode and Presentation Mode put the window full screen, covering the taskbar and the window's frame, and Normal Screen Mode or Full Screen Mode with Menu Bar puts it back (#4365); a window the user made full screen stays so. An unmodified Escape in either Full Screen Mode exits to Normal Screen Mode after any open popup, focused field, tool gesture, ruler-origin drag, floating Tools panel move, edit mode, drawer, flyout or view rotation has taken its Escape; a later Escape exits when that action is finished. This is a VectorCraft choice for both full screen variants, based on the public [shortcut list](https://helpx.adobe.com/illustrator/using/default-keyboard-shortcuts.html); the list does not specify that priority or the return mode. @@ -1034,7 +1040,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur View › Rotate View turns the view to the status bar's preset angles (`view.rotate {angle}`, which takes any angle). View › Rotate View to Selection turns the view to the angle of the selected objects' bounding box, so the box is square to the window (`view.rotateToSelection`). When the view angle changes (a Rotate View drag, the status bar's angle menu, Reset Rotate View or a saved view) and the desktop app renders the frame at the new angle on the render worker, the canvas draws the last frame turned to the new angle until that frame is ready. It used to draw no art until then. While the desktop app's render worker renders the frame for a new view, the parts of the canvas the last frame does not cover after a pan, a zoom-out or a turn show the art from a frame that a second worker renders at a quarter of the resolution, covering twice the canvas's width and height. That frame draws images only from pixels already decoded (an image not yet decoded shows as a light gray box), and it renders large raster effects at the lower resolution a drag uses. Until it is ready, those parts show the pasteboard and the artboards. They used to show only the pasteboard and the artboards until the frame for the new view was ready. - With the view rotated, a second Escape less than a second after the first resets the rotation, as Reset Rotate View does. The first Escape may end something else, such as isolation mode or a path being drawn. The second resets the view only when it has nothing else to end, and an Escape that closes a menu does not count. After a click, or a press of another key that is not a modifier (Shift, Control, Alt/Option or Command), the next Escape counts as the first. With the Rotate View tool chosen, one Escape resets the view. + With the view rotated, an Escape that has nothing else to end resets the rotation, as Reset Rotate View does, with or without a selection, which stays selected. An Escape that ends something else ends only that, and the next Escape resets the view: to reset the view while another tool or feature is in use, Escape is pressed twice ([Rotate canvas view](https://helpx.adobe.com/illustrator/desktop/add-and-import-files/start-a-new-file/rotate-canvas-view.html)). Under VectorCraft's own rule, the things an Escape ends first are isolation mode, pattern editing, Global Edit, a tool flyout, a full screen mode, Presentation Mode, a path being drawn with the Pen, Smart Pen or Curvature tool, the Blend tool's first pick, the Artboard tool, a tool's drag, a menu, a dialog, a text field and a drag of the ruler origin, and the second press may come any time later, after clicks or other keys. With the Rotate View tool, the view resets before a full screen mode ends; with another tool, Escape leaves a full screen mode first, and Shift+Escape, which does not leave it, resets the view. An Escape does not reset the view while About, a progress window or an Appearance row's popup is open, while a pointer button is held, or in the frame a button is let go. It used to reset the view only as the second of two Escape presses less than a second apart. A two-finger rotation on a Mac trackpad turns the view about the pointer once it reaches 5° (Preferences › General › Trackpad Gesture to Rotate View, on by default). On a touch screen a second finger cancels the tool press the first finger began, in the frame it lands or later: the Pencil's stroke or a Selection move is rolled back with no undo entry, and a finger that lands while another is down presses nothing, so a pinch or two-finger pan only zooms and pans (#4198; canvas test `a_second_finger_cancels_the_tool_gesture_the_first_began`). A tool press dropped by a second finger, a long touch or a canceled touch cancels the tool's drag as Escape does: the tool gets back the options it had when the press began (the Polygon tool's sides, set with ↑ and ↓) and they are not stored, a press held still opens no size dialog, a Selection or Artboard tool marquee selects nothing, and the Pen goes on drawing its path without the dropped anchor (canvas tests `a_canceled_touch_drops_the_drag_without_keeping_its_options` and `long_touch_drops_a_tool_press_without_committing_art`; engine tests in `tests::toolsettings`). @@ -1251,7 +1257,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur Cmd/Ctrl-click on the Gradient panel's Gradient Fill box or on the Tools panel's Gradient button resets the gradient of the active Fill or Stroke to the linear White, Black gradient, as one undo step ([Default keyboard shortcuts](https://web.archive.org/web/20260726060015/https://helpx.adobe.com/illustrator/using/default-keyboard-shortcuts.html)). With a gradient stop or a freeform gradient point selected, Alt-clicking a color swatch in the Swatches panel recolors it instead of the inactive Fill or Stroke. - **Freeform gradient colors in their own model:** Object ▸ Expand and Object ▸ Create Gradient Mesh (`object.mesh.create`) mix a freeform gradient's points in the color model they share: points of C50 M20 Y0 K10 give mesh points of C50 M20 Y0 K10, and RGB points keep their values in a working RGB space other than sRGB. The canvas, the gradient chips and the SVG, PDF, EPS and EMF writers mix the points in that model too. PDF and EPS write a gradient whose points are all CMYK, or all Gray in a CMYK file, as a CMYK image, which PDF's Output settings convert as they convert any CMYK image. Points in different models mix in display RGB (on the canvas in a CMYK document that shows transparency, as the inks of each point), and a CMYK document stores the result of Expand as CMYK through the color settings. Points colored along CMYK stops (`paint.editGradient {stops}`, or a CMYK gradient switched to freeform) are CMYK, and so are a point `paint.freeform.splitLine` adds between CMYK points and a point `paint.freeform.addPoint` adds without `color` to CMYK points. Public reference: [Gradients](https://web.archive.org/web/20250714042311/https://helpx.adobe.com/illustrator/using/gradients.html) and [Meshes](https://web.archive.org/web/20250812201019/https://helpx.adobe.com/illustrator/using/meshes.html), which do not state how colors in different models mix; the rule is VectorCraft's own. - - **Strokes:** one stroke-geometry module shared by the canvas, SVG, PDF and Outline Stroke; dotted lines (zero-length dashes draw dots or squares); arrowheads with hollow outlines, tip-on-end or extend-past-end alignment and one opacity for line and head. SVG and PDF export arrowheads, width profiles, brushes and aligned strokes exactly as the canvas draws them; Outline Stroke and the live Outline Stroke effect outline every stroke item as drawn (dashes, heads, profiles, alignment); dashes can be fitted to corners and path ends; width profiles carry through dashes, and their corners take the join. The Stroke panel edits type's character strokes, follows the stroke units (its weight presets are round values in that unit: `0.25 mm`, `0.0625 in`, `1 px`, #426; fields show four decimals in mm, cm and inches, three in points), shows mixed values blank and opens from the Control bar. A width profile library, thirty more arrowheads, and Width Point Edit with multi-select and discontinuous points. Visual bounds and clicks cover the whole painted stroke. Scale Strokes & Effects, Scale Corners and Use Preview Bounds work everywhere, and new art inherits stroke options, a graphic style or the whole last appearance. + - **Strokes:** one stroke-geometry module shared by the canvas, SVG, PDF and Outline Stroke; dotted lines (zero-length dashes draw dots or squares); arrowheads with hollow outlines, tip-on-end or extend-past-end alignment and one opacity for line and head. SVG and PDF export arrowheads, width profiles, brushes and aligned strokes exactly as the canvas draws them; Outline Stroke and the live Outline Stroke effect outline every stroke item as drawn (dashes, heads, profiles, alignment); dashes can be fitted to corners and path ends; width profiles carry through dashes, and their corners take the join. The Stroke panel edits type's character strokes, follows the stroke units (its weight presets are round values in that unit: `0.25 mm`, `0.0625 in`, `1 px`, #426; fields show four decimals in mm, cm and inches, three in points), shows mixed values blank and opens from the Control bar. A width profile library, thirty-one more arrowheads (among them Line Arrow: two arms of the head's weight (stroke weight × arrowhead scale, at least 0.25 pt: the line's weight at 100 % for lines of 0.25 pt or more) at right angles, cut square, #5421), and Width Point Edit with multi-select and discontinuous points. Visual bounds and clicks cover the whole painted stroke. Scale Strokes & Effects, Scale Corners and Use Preview Bounds work everywhere, and new art inherits stroke options, a graphic style or the whole last appearance. - **Brushes (part of #852):** double-clicking a brush in the Brushes panel (or the panel menu's Brush Options…) opens Calligraphic Brush Options (Name; Angle, Roundness and Size, each Fixed, Random, Pressure, Tilt, Bearing or Rotation with its Variation; live previews of the nib and of a light–heavy–light stroke) or Bristle Brush Options (Shape and the bristle sliders); OK edits the brush and every stroke painted with it. The Paintbrush records the pen pressure along each stroke (kept with the path, saved, and joined when a stroke continues a path); a Calligraphic value on Pressure goes from value − variation at the lightest pressure to value + variation at the heaviest, on the canvas and in SVG, PDF and the other exports. Brushes saved before keep their look. Scatter Brush Options (Size, Spacing, Scatter and Rotation, each Fixed, Random between two values, Pressure from the first at the lightest pressure to the second at the heaviest, Tilt, Bearing or Rotation; Rotation relative to Page or Path), Art Brush Options (Width, Scale Proportionately, Stretch to Fit Stroke Length or Stretch Between Guides with the guides' start and end, the four Directions, Flip Along and Across, Overlap) and Pattern Brush Options (Scale, Spacing, the five tiles shown, Flip Along and Across, Stretch to fit, Add space to fit or Approximate path) each have Colorization (None, Tints, Tints and Shades, Hue Shift with its Key Color picked from the art's colours) and a live stroke preview; values from files and commands are clamped to their ranges. Art Brush Options › Overlap places art on each run between sharp corners so folds do not overlap (`ArtBrush.overlap`; `art_brush_overlap_splits_at_corners`). Still to come: Stylus Wheel, pen pressure on macOS where the windowing layer reports none, and tilt, bearing and rotation for Art, Pattern and Bristle brushes and on native Wayland and the web. Under Tints and Tints and Shades, art in black ink alone goes by its ink amount, and a process or gray stroke color's tints and shades stay in that color's model; these are VectorCraft's own rules. Type in a scatter brush's art takes the brush's colorization as its paths do: Tints, Tints and Shades and Hue Shift recolor the characters' solid fills and strokes in each copy the brush draws, and Brush Options' Key Color list, whose first color is Hue Shift's default key, counts the characters' fills and their strokes wider than 0. The Brushes page says that a scatter, art or pattern brush takes its colors from the current stroke color and the brush's colorization method (<https://web.archive.org/web/20241230205225/https://helpx.adobe.com/illustrator/using/brushes.html>) and does not mention type there; recoloring the characters' paints like the art's fills and strokes is VectorCraft's own rule. The Symbol Stainer mixes the characters' strokes of type toward the stain as it mixes their fills. Evidence: `tests::scatter_colorization_recolors_type`, `tests::art_colors_list_the_most_used_first`, `tests::stain_mixes_type_strokes_too` (vectorcraft-brush). @@ -1287,7 +1293,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Transparency:** three-state Knockout Group (on, neutral, off), Opacity & Mask Define Knockout Shape, Page Isolated Blending and Page Knockout Group, on screen and in SVG/PDF. SVG export writes a knockout group of opaque art plainly, without masks, so shapes meeting edge to edge leave no seam; translucent, blended, masked or brushed art knocks out through masks. Blend modes match the standard formulas on screen, in SVG and in PDF, and non-isolated groups blend with the art below. Flatten Transparency with presets, a dialog and a Flattener Preview panel. Flattening for files without transparency (PDF/X-1a, PDF/X-3) in a CMYK document keeps the inks where it rasterizes, as under an image with see-through pixels: the images it makes hold ink amounts, not screen colours the file would separate again, so a C100 M6 Y41 K3 panel stays C100 M6 Y41 K3 there (#2160, `engine/src/cmd/fileio/tests_pdfx.rs`). On the canvas, the renderer no longer draws the picture of the art below back as an image each time it copies the backdrop of a non-isolated group that blends: it keeps that picture and draws the art that follows over it. At 2880 × 1800, 50 translucent groups with Multiply members take 65 ms a frame instead of 299 ms on 8 threads (`vectorcraft-cli bench`), and the frames have the same pixels. Type inside a group, layer, symbol instance, blend or repeat keeps its opacity, blend mode, opacity mask, Opacity & Mask Define Knockout Shape, own effects, perspective and visibility when the effects on the container outline it. Hidden type with a geometry effect of its own is left out of exports. - - **Graphic styles:** styles keep opacity and blend mode, capture groups and type, apply on top with Alt, and link to the objects using them; Redefine, Break Link, Graphic Style Options, Select All Unused, Sort by Name, and Select > Same Graphic Style / Appearance Attribute. The panel has list and thumbnail views with rendered previews, merge, reorder and drag and drop, plus a Control bar Style picker; six generated style libraries save and load as `.vcstyles`. + - **Graphic styles:** styles keep opacity and blend mode, capture groups and type, apply on top with Alt, and link to the objects using them; Redefine, Break Link, Graphic Style Options, Select All Unused, Sort by Name, and Select > Same Graphic Style / Appearance Attribute. The panel has list and thumbnail views with rendered previews, merge, reorder and drag and drop, plus a Control bar Style picker; seven generated style libraries (including Game HUD) save and load as `.vcstyles`. In the Graphic Styles panel, Shift-click selects a range of styles and Ctrl/Cmd-click adds or removes one. - **Several text styles at once:** in the Character Styles and Paragraph Styles panels, Shift-click highlights a range of styles and Ctrl/Cmd-click adds or removes one, without applying them; the panel menu's Select All Unused (`charStyle.unused`, `paraStyle.unused`) highlights the styles no type uses (in the layers, opacity masks, symbols, graph designs, pattern tiles and the art of brushes), never the Normal style; Delete, the button or the menu item, deletes every highlighted style but Normal in one undo step (`charStyle.delete {names}`, `paraStyle.delete {names}`). The menu's Duplicate copies every highlighted style in one undo step and highlights the copies. A highlighted row dragged onto Create New Style or Delete carries every highlighted style: dropped on Create New Style it copies them all and highlights the copies, and dropped on Delete it deletes them all but Normal and clears the highlight; a row from outside the highlight carries only its own style. Public reference: [Character and paragraph styles](https://web.archive.org/web/20261015081534/https://helpx.adobe.com/illustrator/using/character-paragraph-styles.html). - **Load text styles from another document:** the Character Styles and Paragraph Styles panel menus have Load Character Styles… or Load Paragraph Styles… and Load All Styles…, which copy the styles of a document picked in an open dialog, with the swatches and patterns they paint with, in one undo step (`charStyle.load`, `paraStyle.load`, `textStyle.loadAll`); a style the document already has, under its name or a numbered one, is not added again, any other whose name is taken gets a number, and the file's Normal styles are not loaded. Public reference: [Character and paragraph styles](https://web.archive.org/web/20261015081534/https://helpx.adobe.com/illustrator/using/character-paragraph-styles.html). @@ -1394,7 +1400,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur A `.ai`, or a PDF saved with Illustrator's editing data, whose editing data can't be decompressed opens from its PDF part with a warning that its layers weren't read and why, and an export or Save As to its own path asks first (`acknowledgeLoss`), as for a file whose layers the reader can't read (`crates/eps/src/import/tests_native.rs`, `crates/engine/src/cmd/fileio/tests_aiimport.rs`). A `.ai` or EPS opened from its editing data with one object on a shown layer that the reader can't read (an unknown operator inside a group, a pattern fill whose pattern it doesn't have, a symbol instance, a placed file without a usable preview) keeps its layers and groups: in that object's place, its layer gets a group of the page's objects inside the object's box, named after it, with a warning that lists what came in as the page's art and an export or Save As to its own path asking first (`acknowledgeLoss`). The file still opens from its page or PDF part when no box can be found, when live art or another unread object shares the page art inside it, when the object spans two artboards or lies on an artboard that has no page, when no page art lies inside its box, when that page art is inside a page group with a clip, mask, transparency or appearance, when the object holds a frame of threaded type, when the page art uses a pattern, image or swatch that the page lacks or that differs from the editing data's, or when the page art doesn't carry the object's transparency (#4806; `crates/eps/src/import/tests_native.rs`, `crates/engine/src/cmd/fileio/tests_aiimport.rs`). A `.ai` or EPS opened from its editing data with one object on a shown layer that the reader can't read (an unknown operator inside a group, a pattern fill whose pattern it doesn't have, a symbol instance, a placed file without a usable preview) keeps its layers and groups: in that object's place, its layer gets a group of the page's objects inside the object's box, named after it, with a warning that lists what came in as the page's art and an export or Save As to its own path asking first (`acknowledgeLoss`). The file still opens from its page or PDF part when no box can be found, when live art or another unread object shares the page art inside it, when the object spans two artboards, or when the page art doesn't carry the object's transparency (#4806; `crates/eps/src/import/tests_native.rs`, `crates/engine/src/cmd/fileio/tests_aiimport.rs`). - In a `.ai` opened from its editing data, an envelope made with a warp, a mesh or a top object opens as a live envelope of its contents, with its warp style, bend and distortions, its mesh points and handles or its top object's outline, its Envelope Options, its Fidelity and whether its contents are being edited. When Distort Appearance is on and the size the file saves for the contents matches their bounds with strokes, the contents map from that stroked box, until an edit in Edit Contents changes how far the strokes reach; VectorCraft's new envelopes map from the geometric box, as do contents with no width or no height, such as a single straight line. An envelope that can't be read, or that VectorCraft draws differently from the file's drawn art, keeps that drawn art, with a note. An envelope of type keeps its drawn art, with its type hidden (`crates/eps/src/import/ai/tests.rs`, `crates/eps/src/import/tests_native.rs`). + In a `.ai` opened from its editing data, an envelope made with a warp, a mesh or a top object opens as a live envelope of its contents, with its warp style, bend and distortions, its mesh points and handles or its top object's outline, its Envelope Options, its Fidelity and whether its contents are being edited. When Distort Appearance is on and the size the file saves for the contents matches their bounds with strokes, the contents map from that stroked box, until an edit in Edit Contents changes how far the strokes reach; VectorCraft's new envelopes map from the geometric box, as do contents with no width or no height, such as a single straight line. An envelope that can't be read, or that VectorCraft draws differently from the file's drawn art, keeps that drawn art, with a note. An envelope of type keeps its drawn art, with its type hidden and a note that says the type isn't editable (#3179; `crates/eps/src/import/ai/tests.rs`, `crates/eps/src/import/tests_native.rs`). In a `.ai` opened from its editing data, Convert to Shape on a whole path or type object opens as a live Rectangle, Rounded Rectangle or Ellipse effect with its Absolute or Relative size, its corner radius, its place among the object's effects and whether it is hidden. A relative size in the file is added to each side. A relative Ellipse, or a setting VectorCraft doesn't read, keeps the drawn art (`crates/eps/src/import/ai/style/tests.rs`, `crates/eps/src/import/ai/tests.rs`, `crates/eps/src/import/tests_native.rs`). In a `.ai` opened from its editing data, Bas Relief in an art style takes its Detail, Smoothness and Light direction from the style's settings block, and an object other than type with it opens as itself with the live effect. A settings block that VectorCraft can't read (malformed, another effect's, a value out of range or a key it doesn't know) keeps the object's drawn look (part of #637; [raster effects reference](https://helpx.adobe.com/illustrator/desktop/special-effects-styles/apply-filter-effects/raster-effects-reference.html), [Photoshop File Formats Specification](https://www.adobe.com/devnet-apps/photoshop/fileformatashtml/), [scripting the filter gallery](https://community.adobe.com/questions-712/scripting-support-for-the-filter-gallery-1064646); `crates/eps/src/import/ai/style/tests.rs`, `crates/eps/src/import/ai/tests.rs`). PDF export and `.ai` saves write a page with a side longer than 14,400 pt with a `UserUnit` (PDF 1.6), its longer side divided by 14,400 and rounded up to the next thousandth, so that no side is longer than 14,400 units (ISO 32000-1, Annex C.2); in PDF 1.3 to 1.5 files and PDF/X files such a page is written in points. @@ -1910,7 +1916,9 @@ The custom dictionary and Ignore All followed (2026-11-09), as the same page des Auto Spell Check followed (2026-11-09): the same page has Edit › Spelling › Auto Spell Check underline potential spelling errors with a red line as you type, and says it isn't available for text with effects applied (#4936). `edit.autoSpellCheck` turns it on and off (off at first, saved with the view settings); the canvas draws a red wavy line under each word `text.spelling.check` would list in the visible type, leaves out type with an effect shown on it or on its fills and strokes, and checks a type object again when it is edited, when the custom dictionary changes and when Ignore All adds a word (`ui-egui/src/canvas/tests.rs`, `auto_spell_check_*`; `tests/spelling.rs`). The dialogs remain. -The right-click followed (2026-11-10), as the same page's "Correct spelling errors during Auto Spell Check" describes it: right-click a word with a red underline, then choose a suggested word, Ignore All to skip it in the current document, or Add to Dictionary (#4936). The canvas context menu lists the words `text.spelling.suggest` gives for it in its run's language, each replacing the word with `text.editRange` as one undo step, or No Suggestions; then Ignore All (`text.spelling.ignoreAll`) and Add to Dictionary (`text.spelling.addWord`). It lists nothing for a word that is right, with Auto Spell Check off, or once the word under the right-click has changed (`ui-egui/src/tests/contextmenu.rs`). The dialogs and the context menu's Spelling › Auto Spell Check remain. +The right-click followed (2026-11-10), as the same page's "Correct spelling errors during Auto Spell Check" describes it: right-click a word with a red underline, then choose a suggested word, Ignore All to skip it in the current document, or Add to Dictionary (#4936). The canvas context menu lists the words `text.spelling.suggest` gives for it in its run's language, each replacing the word with `text.editRange` as one undo step, or No Suggestions; then Ignore All (`text.spelling.ignoreAll`) and Add to Dictionary (`text.spelling.addWord`). It lists nothing for a word that is right, with Auto Spell Check off, or once the word under the right-click has changed (`ui-egui/src/tests/contextmenu.rs`). The dialogs remain. + +The page's other way to turn Auto Spell Check on followed (2026-11-10): right-click the text and choose Spelling › Auto Spell Check (#4936). A right-click on type (which selects it) has a Spelling submenu with Auto Spell Check, which runs `edit.autoSpellCheck` as Edit › Spelling does. The context menu draws no check marks, its toggles saying what they do (Show Rulers, Hide Guides), but a submenu that holds only toggles shows them, so Auto Spell Check is checked while it is on; other art has no Spelling submenu (`right_click_on_type_turns_auto_spell_check_on_and_off`). ## Control bar: Paragraph section while type is selected (2026-11-06) @@ -1928,6 +1936,10 @@ Edit › Copy and Cut put the selected ruler guides on the clipboard, with the s | Date | Change | Summary | |---|---|---| +| 2026-11-10 | minor | Bundled content: built-in Game HUD graphic style library; style libraries evidence updated; ~34% → ~36%; more built-in graphic-style libraries remain. | +| 2026-11-10 | minor | Bundled content: built-in Map Markers symbol library (Pin, Flag, Crosshair, Checkpoint); symbol libraries evidence updated; ~32% → ~34%; more built-in symbol libraries remain. | +| 2026-11-10 | minor | Type advanced: Spelling › Auto Spell Check in the context menu of type, checked while it is on, #4936; evidence added; the dialogs remain; scores and hours unchanged. | +| 2026-11-10 | minor | Type advanced: right-click suggestions, Ignore All and Add to Dictionary on a word Auto Spell Check underlined, #4936; evidence added; the dialogs remain; scores and hours unchanged. | | 2026-11-10 | minor | Raster effects: the Effect Gallery shows a thumbnail of each filter and a preview of the visible stack (or the filter being browsed) inside the dialog, both an original landscape drawing passed through the filter ([Filter Gallery overview](https://helpx.adobe.com/photoshop/desktop/effects-filters/get-started-with-filters/filter-gallery.html)); 52% → 55%, 1–2 h → none (estimated). The canvas preview and one-undo OK are unchanged. Headline numbers unchanged. | | 2026-11-09 | minor | Canvas: a 3D effect changed on type or a group redraws where its solid was, measured by the effect's art through the renderer that drew the frame; exports and Object › Rasterize take the solid of 3D type; Fit to Artwork Bounds and per-artboard SVG export measure all artboards through one renderer; a 3D effect on a fill or stroke that builds nothing no longer overflows the stack on the canvas, in Object › Rasterize and in raster and EPS exports (evidence in Feature revisions). Scores and estimates unchanged. | | 2026-11-09 | minor | Type advanced: Auto Spell Check (`edit.autoSpellCheck`), #4936; evidence added; the dialogs and the right-click Spelling menu remain; scores and hours unchanged. | diff --git a/docs/type-parity.md b/docs/type-parity.md index bb64f08c47..ef32c497a1 100644 --- a/docs/type-parity.md +++ b/docs/type-parity.md @@ -1,6 +1,6 @@ # Type parity -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-10 · **Change:** minor (remaining language-list additions and public sources, #4943; right-click on a word Auto Spell Check underlined: its suggestions, Ignore All and Add to Dictionary, #4936; previously minor: Auto Spell Check: `edit.autoSpellCheck` underlines the unknown words, #4936; previously minor: PDF marked-text export (#6309): compatible glyphs stay on one layout line with per-glyph offsets; scores and estimates unchanged; paint-only Arabic harakat keep joining with GDEF-mark ownership and Insert Kashidas base-letter paint; scores and estimates unchanged; custom dictionary and Ignore All: `text.spelling.addWord`, `removeWord`, `changeWord`, `dictionary` and `ignoreAll`, #4936; previously minor: spell check engine: `text.spelling.check` and `text.spelling.suggest` on craft-proof, #4936; previously minor: right-aligned area type sets the text after a line's last tab against the right edge; a soft return in justified type no longer keeps its line from being justified; 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) · **Target:** Adobe Illustrator 2026 (30.x) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-10 · **Change:** minor (remaining language-list additions and public sources, #4943; previously minor: Direct Selection shows and drags the direction handles of type on a path's path, #3565; 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: Auto Spell Check: `edit.autoSpellCheck` underlines the unknown words, #4936; previously minor: PDF marked-text export (#6309): compatible glyphs stay on one layout line with per-glyph offsets; scores and estimates unchanged; paint-only Arabic harakat keep joining with GDEF-mark ownership and Insert Kashidas base-letter paint; scores and estimates unchanged; custom dictionary and Ignore All: `text.spelling.addWord`, `removeWord`, `changeWord`, `dictionary` and `ignoreAll`, #4936; previously minor: spell check engine: `text.spelling.check` and `text.spelling.suggest` on craft-proof, #4936; previously minor: right-aligned area type sets the text after a line's last tab against the right edge; a soft return in justified type no longer keeps its line from being justified; 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) · **Target:** Adobe Illustrator 2026 (30.x) Type is Illustrator's largest single area by use (weight 13 of 105 across "Type core" and "Type advanced" in [target-app-parity.md](target-app-parity.md)). This checklist lists the features one by one. Status is from the @@ -25,7 +25,7 @@ against Illustrator's public documentation; **estimated** unless noted. | Area Type Options (rows, columns, inset, first baseline, Text Flow by rows or by columns, Auto Size, Shrink Text to Fit) | done | Text Flow fills the cells down each column first (By Columns, the default, as files from before it open) or across each row first (By Rows), in the dialog and `text.areaOptions {flow}` (#4978); the commands that make or restyle type say when it does not fit its frame; MCP `add_text` takes Auto Size and Shrink Text to Fit (#1471) | | Threaded text, Fit Headline, Text Wrap | done | Fit Headline sees wrapping in a frame one line tall (#1444); a thread holds area type and type on a path in any mix, as Illustrator links type in an area or along a path ([help](https://helpx.adobe.com/illustrator/using/manage-text-area.html)) | | Threading from the ports: selected area type and type on a path show an in port and an out port, empty, with an arrow on a side where the frame is threaded, or with a red "+" in the out port when the text doesn't fit; a click on either port loads the text; a click on a closed path, area type or type on a path threads into it, a click on empty canvas makes a frame of the same kind, shape and size there, a drag draws a rectangular frame; the frame placed comes after the clicked one from its out port and before it from its in port (the story then starts there); Escape or another tool cancels; a double-click on a threaded port breaks the thread there | partial | #2572: the Selection tool, `text.thread.add {from, to?, rect?, at?, before?}`, as the reference app's help describes ports and threading ([archived help, Threading text between objects](https://web.archive.org/web/20210119051048/https://helpx.adobe.com/illustrator/using/creating-text.html), [create text threads](https://helpx.adobe.com/illustrator/desktop/design-with-text/add-manage-text/create-text-threads-between-objects.html)); area type's in port sits on the left side below the top-left corner, type on a path's just before its start bracket; Show Text Threads draws its lines between the same ports; with more than 1,000 such objects selected no ports are drawn. a double-click on a port where the frame is threaded breaks the thread there, the story flowing into the frames before the break and the frames after it left empty, still threaded with each other when two or more (`text.thread.break`, [archived help](https://web.archive.org/web/20220127090642/https://helpx.adobe.com/illustrator/using/creating-text.html)). Remaining: the ports only take clicks with the Selection tool, and the loaded cursor borrows the I-beam until it's drawn | -| Type on a Path effects and options; brackets | done | #429; Type on a Path Options has a Preview checkbox (#5360, as public tutorials of the dialog show) | +| Type on a Path effects and options; brackets | done | #429; Type on a Path Options has a Preview checkbox (#5360, as public tutorials of the dialog show); Direct Selection shows the anchors and direction handles of selected type on a path's path and drags both, the brackets keeping their fractions of the path and the text reflowing along it (#3980, #3565; `text.reshapePath`, `text.setPathHandle`), as the [Direct Selection page](https://helpx.adobe.com/illustrator/using/tool-techniques/direct-selection-tool.html) describes for a path | | Character and Paragraph panels, styles with overrides | done | Character-style Auto-leading resets, partial definitions, local leading overrides, override markers, Undo/Redo and native serialization have regression coverage; differing paragraph alignments leave the shared alignment buttons unselected (headless regressions, full integration CI and visual review pass); mixed-value display for other paragraph fields remains missing. Double-clicking a user character style's row opens its Character Style Options, and the dialog keeps a fixed width while its sections scroll when the window is shorter, so its buttons stay on screen; a paragraph style's row opens its Paragraph Style Options, the rename dialog the panel menu opens. Evidence: `panels::text_styles::tests::double_clicking_a_character_style_row_opens_its_options`, `dialogs::char_style_options::tests::the_sections_scroll_in_a_window_shorter_than_the_general_list` | | Copy or Cut selected characters, then paste as separate text art | done | A Type-range copy keeps the selected characters' font family, size and color when pasted on the canvas after leaving text editing, in the same document or another. On desktop the clipboard offers plain text to text consumers and rich art for canvas Paste; Paste Without Formatting while editing uses the destination text's style. `tests::clipboard::type_range_copy_stays_styled_when_pasted_as_art` (#5636) | | Character size and horizontal scale after object/group scaling | done | #1034: fields and setters compensate the stored affine; point size follows the transformed em-height axis, not the glyph ink bounds. Range edits, keyboard increments, leading and baseline shift use document points; rotation, reflection and shear remain editable. | @@ -47,7 +47,7 @@ against Illustrator's public documentation; **estimated** unless noted. | Hyphenation… and Justification… options | done | Eleven Indian languages use attributed patterns and preserve syllables in both composers (#4947). Hyphenation… (`ui.hyphenation`, `text.setFormat`) sets each paragraph's Words Longer Than, After First, Before Last, Hyphen Limit, Hyphenation Zone (Single-line Composer only) and Hyphenate Capitalized Words, and paragraph styles carry them (#2310). Justification… (`ui.justification`, `text.setFormat`, #2755) sets Word Spacing, Letter Spacing and Glyph Scaling (Minimum, Desired, Maximum), Auto Leading and Single Word Justification; Desired applies to every line, justified lines and the Every-line Composer use the ranges. Vertical type isn't glyph scaled; type on a path doesn't use them. Auto Leading also sets the Leading the Character panel shows for Auto type, the leading Alt+↑/↓ (`type.step`) steps from, per paragraph, and the lines Fill with Placeholder Text counts. Evidence: `crates/text/src/tests/justify.rs`, `dialogs::justification::tests`, `tests_prefs::auto_leading_steps_and_fills_from_the_paragraph_auto_leading`, `panels::character` test `leading_field_shows_the_paragraph_auto_leading` | | Tab stops and leaders; Tabs panel | partial | Tabs panel and stops with leaders in the model (`text.tabs.set`); a stop drags from where the press landed (#1458); leaders fill the tab's gap, repeated on a grid so they line up from line to line (#1877); Ctrl-dragging a stop (Command on macOS) moves all the stops together; in right-aligned area type the text before a line's last tab sits at its stops, from the left edge, and the text after it against the right edge, as Illustrator's own layout in a user's `.ai` sets a price list (evidence: `tests::right_aligned_area_type_sets_the_text_after_its_last_tab_against_the_edge`; centred and justified lines are still aligned as a whole) | | Hidden characters (Show Hidden Characters) | done | `type.hiddenCharacters` | -| Spell check (Check Spelling, Auto Spell Check, custom dictionary) | partial | the engine (#4936): `text.spelling.check` lists the unknown words of the document's type, each run in its Language, at the bytes `text.editRange` changes, and `text.spelling.suggest` gives suggestions, both from craft-proof, each paragraph on its own (English from the first dictionary it finds: a Hunspell dictionary in the user's dictionaries folder, the SCOWL dictionary built in from craft-i18n, a system Hunspell dictionary, and last the public-domain Moby word list built into it; other languages from the dictionaries craft-proof finds for them). The custom dictionary commands are done: `text.spelling.addWord`, `removeWord` and `changeWord` (Add, and Edit Custom Dictionary's Add, Delete and Change), and `text.spelling.dictionary` lists the words, saved to `Custom Dictionary.txt` beside the preferences; Ignore All: `text.spelling.ignoreAll` skips a word in the active document while it is open. Auto Spell Check is done: Edit › Spelling › Auto Spell Check (`edit.autoSpellCheck`, off at first, saved with the view settings) draws a red wavy line under the unknown words of the visible type, leaves out type with effects, and follows edits, the custom dictionary and Ignore All. A right-click on an underlined word lists the words its dictionary suggests (each replaces it in one undo step, `text.editRange`), or No Suggestions, then Ignore All and Add to Dictionary. The Check Spelling and Edit Custom Dictionary dialogs and the context menu's Spelling › Auto Spell Check remain. Evidence: `crates/engine/src/tests/spelling.rs`, `crates/ui-egui/src/canvas/tests.rs` (`auto_spell_check_*`), `crates/ui-egui/src/tests/contextmenu.rs` (the right-click). | +| Spell check (Check Spelling, Auto Spell Check, custom dictionary) | partial | the engine (#4936): `text.spelling.check` lists the unknown words of the document's type, each run in its Language, at the bytes `text.editRange` changes, and `text.spelling.suggest` gives suggestions, both from craft-proof, each paragraph on its own (English from the first dictionary it finds: a Hunspell dictionary in the user's dictionaries folder, the SCOWL dictionary built in from craft-i18n, a system Hunspell dictionary, and last the public-domain Moby word list built into it; other languages from the dictionaries craft-proof finds for them). The custom dictionary commands are done: `text.spelling.addWord`, `removeWord` and `changeWord` (Add, and Edit Custom Dictionary's Add, Delete and Change), and `text.spelling.dictionary` lists the words, saved to `Custom Dictionary.txt` beside the preferences; Ignore All: `text.spelling.ignoreAll` skips a word in the active document while it is open. Auto Spell Check is done: Edit › Spelling › Auto Spell Check (`edit.autoSpellCheck`, off at first, saved with the view settings) draws a red wavy line under the unknown words of the visible type, leaves out type with effects, and follows edits, the custom dictionary and Ignore All. A right-click on an underlined word lists the words its dictionary suggests (each replaces it in one undo step, `text.editRange`), or No Suggestions, then Ignore All and Add to Dictionary, and a right-click on type has Spelling › Auto Spell Check, checked while it is on. The Check Spelling and Edit Custom Dictionary dialogs remain. Evidence: `crates/engine/src/tests/spelling.rs`, `crates/ui-egui/src/canvas/tests.rs` (`auto_spell_check_*`), `crates/ui-egui/src/tests/contextmenu.rs` (the right-click). | | Smart Punctuation, Change Case, Find & Replace | done | | | 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 | @@ -80,6 +80,8 @@ Character Styles menu New/Redefine and footer New capture the first selected cha | Date | Change | Summary | |---|---|---| +| 2026-11-10 | minor | Type on a path (#3565): Direct Selection shows the direction handles of selected type on a path's path, as of a path selected whole, and drags them (`text.setPathHandle`; Alt: one side, Shift: 45° steps); the text reflows along the new curve. Scores and estimates unchanged. | +| 2026-11-10 | minor | Spelling in the canvas context menu (#4936): a right-click on type has Spelling › Auto Spell Check, checked while it is on; the Check Spelling and Edit Custom Dictionary dialogs remain. Scores and estimates unchanged. | | 2026-11-10 | minor | Spelling in the canvas context menu (#4936): a right-click on a word Auto Spell Check underlined lists its suggestions, Ignore All and Add to Dictionary; the Check Spelling and Edit Custom Dictionary dialogs remain. Scores and estimates unchanged. | | 2026-11-09 | minor | Auto Spell Check (#4936): Edit › Spelling › Auto Spell Check (`edit.autoSpellCheck`) underlines the unknown words of the visible type, without type with effects; the Check Spelling and Edit Custom Dictionary dialogs and the right-click Spelling menu remain. Scores and estimates unchanged. | | 2026-11-09 | minor | PDF marked-text export (#6309): compatible glyphs stay on one layout line with per-glyph offsets; scores and estimates unchanged. Decoded stream and placement regressions; reader ActualText (#6165), styled clusters and external viewer validation remain separate. | diff --git a/docs/ui-parity.md b/docs/ui-parity.md index f2e1274fa6..3a8abfd265 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -4,6 +4,8 @@ > Numeric spinner update (2026-11-10): held mouse arrows repeat past the click timeout; scores and estimates unchanged (#6307). +> **Flyout update:** 2026-11-06 — resizable icon-strip flyouts and bottom-aligned panel footers (#5713); scores and estimates unchanged. + ## Feature submission evidence Numeric fields step on wheel hover without taking keyboard focus (#5949). Arrow keys still require focus; modifiers, units, limits, mixed values and existing rounding stay in the shared stepping path. Headless regressions in `tests/numfields.rs` cover hovered unfocused fields, focused fields, trackpad accumulation and panel scroll exclusion. Scores and estimates unchanged. @@ -11,6 +13,8 @@ Numeric fields step on wheel hover without taking keyboard focus (#5949). Arrow | 2026-11-06 | minor | Opening a file that takes longer than 0.4 s shows a progress window: the file name, a moving bar (reading reports no steps), how many more files wait, Cancel (Esc; the file doesn't open) and Continue in Background (`file.cancelOpen`, `file.openInBackground`); it never opens over another dialog or progress window (part of #5930); scores and estimates unchanged | Raster rendering fits and preflattens curved stroke outlines more tightly only below four times the raster tolerance, retaining thin-band coverage without changing stroke weight or vector export geometry. Current cached character/object outlines, cropped long strokes, gradient clips and effect rasters share the helper; cropped-region reuse and guarded flattening remain. The unchanged `fractional_curved_strokes_retain_coverage_between_notches` regression covers fractional weights, rotation, phase, opacity and f32-rounded endpoints. This is a quality/cost tradeoff, not a speed claim. Scores and estimates unchanged. +Icon-strip flyouts resize from the canvas-side edge and bottom, keeping the icon-column edge anchored (#5713). Independent group heights and flyout widths persist in workspaces; saved heights override content fitting while untouched heights still fit content. Shared panel button bars and the Glyphs font row stay at the bottom after enlargement; the Artboards list grows into the extra space. Regressions: `panel_docking::tests::glyphs_and_artboards_flyouts_keep_user_sizes` and `expanded_panel_footers_stay_at_the_bottom_with_short_and_long_lists`. Scores and estimates unchanged. + **PR #3273 revision — 2026-11-04:** Thin curved stroke coverage ported to the current raster-only cache, cropped-long-stroke and effect paths with guarded flattening; vector export geometry unchanged. Scores and estimates unchanged. Group Selection keeps an already selected component selected during a drag; a completed click still adds its next enclosing group. The current Direct Selection click/release machinery is shared, preserving compound-member picks, Shift deselection, isolation and masked-art dragging. Outline Stroke continues to preserve all original fills, including open contours; the change does not remove fills. Regressions: `group_selection_distinguishes_selected_leaf_drags_from_clicks` and `outline_fill_and_stroke_move_independently_with_group_selection` cover tool events, independent component movement and Undo/Redo. Scores and estimates unchanged. @@ -59,6 +63,7 @@ Artboard Options forwards the active Artboard tool's Scale Artwork with Artboard | 2026-11-06 | minor | Shape tools: a press on the selection's centre point (Show Center) moves the selection, also where no art is painted, and a press in the rotate zone just outside a bounding-box corner turns it about the centre, both as the Selection tool's do (#5477); the Selection tool takes its centre point too, so an unfilled shape moves instead of starting a marquee; scores and estimates unchanged | | 2026-11-06 | minor | Transform fields: one Tab moves from one numeric field to the next in the Transform panel, the Properties panel's Transform section and the Control bar — a field's scrub label was a second, invisible tab stop, and the W/H link between W and H is now made after the fields, so it stays a tab stop after them; scores and estimates unchanged | | 2026-11-06 | minor | Scrubby labels: the Control bar's Stroke: and Opacity: and the Properties panel's Stroke, links to their panels, scrub the field after them as other labels do; a click still opens the panel (#4088); scores and estimates unchanged | +| 2026-11-06 | minor | Icon-strip flyouts resize on their free edges and retain sizes with workspaces (#5713); saved heights beat auto-fit; panel footers stay at the bottom after enlargement. Scores and estimates unchanged. | | 2026-11-05 | minor | Direct Selection: Shift-click picks several points of a blend's spine and dragging one moves them all, with the key objects on them, in one undo step (#5285); scores and estimates unchanged | | 2026-11-05 | minor | Direct Selection: Cmd/Ctrl held lends the Selection tool, whose bounding box shows while the key is down over objects selected whole; its handles scale and rotate, and a Cmd drag moves the whole object with its direct-selected anchors kept (#3901); scores and estimates unchanged | | 2026-11-05 | minor | Join tool: scrubbing over the ends of two crossing open paths that run past the crossing trims those ends and joins the paths there with a corner, instead of drawing a segment between the ends (#5844); scores and estimates unchanged | @@ -155,6 +160,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 | +| 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 | | Layers panel lists a blend's spine (#4820) | done | an open blend shows a `<Path>` row below its key objects, where Release leaves the spine; a click selects the blend (Shift/Cmd toggles it) so Direct Selection edits the spine; a locked blend's row selects nothing; no row while searching or filtering (`a_blends_spine_is_a_row_below_its_keys_that_selects_the_blend`) | | Layers panel: a layer whose Layer Options › Print is off shows its name italic (#5739) | done | the panel row and its drag ghost; a printing layer stays upright, and Print on again restores it; `panels::layers` test `a_layer_that_does_not_print_has_its_name_italic` | | Blend spine Anchor Point conversion and handle editing (#2544) | implemented | symmetric handles, independent drag/retraction, visible-handle policy and selection/stacking covered by tool and engine regressions; Windows native canvas checks and screenshots reviewed in PR #2643 | @@ -429,6 +435,7 @@ next unit in the order a right-click on a ruler lists them, from Feet back to Po | Preferences › General › Constrain Angle | done | arrow keys and Shift drags along the turned axes; the Rectangle, Rounded Rectangle, Ellipse and grid tools, point and area type and the shape size dialogs draw along them with the bounding box turned; Shift-drawn polygons and stars keep the turned base orientation; the Line Segment tool's Shift steps count from it (#394, <https://helpx.adobe.com/illustrator/desktop/manage-objects/arrange-objects/rotate-objects-by-specific-angles.html>); arcs, spirals, flares and Pen paths are not turned | | Tabs panel: a stop drags from where the press landed, a stop just added included | done | #1458 | | Outline view keeps template layers in Preview, dimmed | done | #1486; a picture placed to be traced stays visible under the outlines | +| Outline view draws on a white canvas, the artboards as their edges | done | Outline shows only the paths ([Outline mode](https://helpx.adobe.com/illustrator/desktop/get-started/learn-the-basics/preview-artwork-as-outlines.html)). VectorCraft's own rule for the canvas: in every interface brightness and Canvas Color the whole canvas is white, pasteboard included; the artboards draw no paper (no Simulate Colored Paper or artboard color, and no paper with Hide Artboards); the artboard names and the ruler origin's crosshair are dark gray; split views and floating windows follow their own view. Tests `outline_draws_on_a_white_canvas_with_artboards_as_edges`, `outline_draws_no_colored_paper`, `a_pane_draws_its_own_views_outline`, `the_ruler_origin_crosshair_shows_on_the_outline_canvas` | | Arrange Tools add-on (VectorCraft addition): Object › Plug-ins › Arrange Tools runs Arrange in Grid… (grid by row, one row or one column; columns, H and V spacing, Center on Artboard; Preview), Swap Objects, Swap Objects and Sizes, Replace with Top Object… (Actual Size, Bounds or Bounds (Fit Proportionally); Keep Original; Scale Strokes & Effects; Preview), Set Size of Each… (Width and Height each ticked on or off, Constrain Width and Height Proportions with one side, the reference point, Scale Strokes & Effects; Preview) and Zoom to Selection, each one undo step | done | `addon.arrange.*`, `crates/engine/src/cmd/addons/arrange.rs`, `crates/ui-egui/src/addons/arrange.rs` and their tests; not a feature of the reference app, so it is not scored | | Arrange Tools add-on (VectorCraft addition): Object › Plug-ins › Arrange Tools › Group Overlapping Objects groups the selected objects whose visual bounds overlap or touch (chains included, within one layer or group), each group at its frontmost member's stacking place, one undo step | done | #4928; `addon.arrange.groupOverlapping`, `crates/engine/src/cmd/addons/arrange.rs` and its tests; not a feature of the reference app, so it is not scored | | Arrange Tools add-on (VectorCraft addition): Object › Plug-ins › Arrange Tools › Randomize Opacity… gives each selected object its own opacity at random between Minimum and Maximum (%), with a Seed that repeats it and Preview, one undo step | done | #4925; `addon.arrange.randomizeOpacity`, `crates/engine/src/cmd/addons/arrange.rs`, `crates/ui-egui/src/addons/arrange.rs` and their tests; not a feature of the reference app, so it is not scored |